Use LINQ and get field values by name

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.
 
F

Frans Bouma [C# MVP]

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#)
------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top