Use LINQ and get field values by name

  • Thread starter Thread starter Anton Bar
  • Start date Start date
A

Anton Bar

Hi all,

I have the following problem. I have a database table that I want to read
using LINQ and being able to access field values by name, like this:

var languages = from lg in context.SystemLanguages select lg;
foreach (SystemLanguage lang in languages)
{
// now I'd like to do smth like this:
string name = lang.Field(sFieldName);
.........
}

The problem is that the "sFieldName" string is built dynamically, so I
cannot use the predefined strongly typed properties!!!

Any bright ideas?

Thanks in advance,
Anton.
 
Anton said:
Hi all,

I have the following problem. I have a database table that I want to
read using LINQ and being able to access field values by name, like
this:

var languages = from lg in context.SystemLanguages select lg;
foreach (SystemLanguage lang in languages)
{
// now I'd like to do smth like this:
string name = lang.Field(sFieldName);
.........
}

The problem is that the "sFieldName" string is built dynamically, so
I cannot use the predefined strongly typed properties!!!

Any bright ideas?

TypeDescriptor.GetProperties(typeof(SystemLanguage))

this will get you property descriptors. You can use a property
descriptor with 'lang' to obtain a property's value by calling GetValue
on the property descriptor object.

So you do something like:
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(SsytemLanguage));
foreach(SystemLanguage lang in languages)
{
string name = (string)properties[sFieldName].GetValue(lang);
}

It's not as fast as reading normal properties, but it shows you what
the possibilities are. :)

FB

--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
 
Back
Top