If I have a list of objects, eg
List<CustomClass> dataList = new List<CustomClass>
{
new CustomClass { Field1 = "a1", Field2 = "a2", Field3 = "a3", Field4 = "a4", Field5 = "a5"},
new CustomClass { Field1 = "b1", Field2 = "b2", Field3 = "b3", Field4 = "b4", Field5 = "b5"},
new CustomClass { Field1 = "c1", Field2 = "c2", Field3 = "c3", Field4 = "c4", Field5 = "c5"},
new CustomClass { Field1 = "d1", Field2 = "d2", Field3 = "d3", Field4 = "d4", Field5 = "d5"},
};
public class CustomClass
{
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; }
}
and a list of selected property names, eg
List<string> propertiesSelectedList = new List<string> { "Field1", "Field3", "Field5" };
How can I dynamically Select
only the required properties at runtime using LINQ?
Eg equivalent of the following but at runtime using the values in list propertiesSelectedList
?
var newListWithSelectedProperties = dataList.Select(n => new { n.Field1, n.Field3, n.Field5 }).ToList();
The final output would hopefully would look like this list...
List<T> newdataList = new List<T>
{
new T { Field1 = "a1", Field3 = "a3", Field5 = "a5"},
new T { Field1 = "b1", Field3 = "b3", Field5 = "b5"},
new T { Field1 = "c1", Field3 = "c3", Field5 = "c5"},
new T { Field1 = "d1", Field3 = "d3", Field5 = "d5"},
};