Consider we have this class :
public class Data
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
public string Field5 { get; set; }
}
How do I dynamically select for specify columns ? something like this :
var list = new List<Data>();
var result= list.Select("Field1,Field2"); // How ?
Is this the only solution => Dynamic LINQ ?
Selected fields are not known at compile time. They would be specified at runtime
Using Reflection and Expression bulid can do what you say. Example:
I have generate my own class for same purpose of usage.
github gist : https://gist.github.com/mstrYoda/663789375b0df23e2662a53bebaf2c7c
It generates dynamic select lambda for given string and also support for two level nested properties.
Example of usage is :
It compiles the lambda as below:
You can also find my quesion and answer here :c# - Dynamically generate linq select with nested properties
You must use reflection to get and set property value with it's name.
And here is GetPropValue() method
You can do this by dynamically creating the lambda you pass to
Select:
Then you can use it like this:
In addition for Nicholas Butler and the hint in comment of Matt(that use
T
for type of input class), I put an improve to Nicholas answer that generate the property of entity dynamically and the function duos not need to sendfield
as parameter.For Use add class as blow:
The
DynamicSelectGenerator
method get entity with typeT
, this method have optional input parameterFields
that if you want to slect special field from entity send as a string such as"Field1, Field2"
and if you dont send anything to methid, it return all of the fields of entity, you could use this method as below :(Assume that you have a
DbContext
with nameAppDbContext
and the context have an entity with nameSampleEntity
)Another approach I've used is a nested ternary operator:
The ternary operator requires that each field be the same type, so you'll need to call .ToString() on any non-string columns.