3
votes

I have List<Employee> listEmployees

I want to select some dynamic columns which are not known at compile time, like:

 var result = from l listEmployees
              select "" 

I tried listEmployees.select("Name");

But it throws an error saying:

'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How can I select only the columns which are determined at runtime?

3
@SLaks For performance sakes, like if I need just a few columns out of 300 columns in the table, is it not better to select just the columns I need? Or are you saying that it is still good enough (performance wise) to select the entire row, and use the columns needed?Sнаđошƒаӽ
@Sнаđошƒаӽ: You should specify the columns you need at compile time. If you don't know them at compile time, you probably shouldn't be using LINQ.SLaks

3 Answers

7
votes

You're looking for Dynamic LINQ.

1
votes

You could use dynamic linq, it is a open source project which I have used for really dynamic linq queries:

Article on Scott's Blog

Hope that helps.

1
votes

Here's a really horrible approach that works

var result = from l in listEmployees
             select l.GetType().GetProperty(propertyName).GetValue(l, null);

Where propertyName is whatever string you pass at runtime.

Of course, you probably want to extract the bit after the select as a method and add some checking.