Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select Dynamic column from List

Tags:

c#

linq

I want to select columns dynamically from List as following. So what could be the best way?

//a objects list
List<DashBoard> dashboardlist = (List<DashBoard>)objList;  
string strColumns = "RecDate,ModifiedDate";
objList = (from obj in dashboardlist select new { strColumns }).ToList();

///////////// Ok,Just forget Object List say I have database table which have number of column ID,Name,Age,sex,etc ..Then I have columnList to display and the columnList is change according to condition . SO I have List people; and List columnTemplate; so now I want to select the column based on the template .

like image 376
DKD Avatar asked Nov 22 '12 12:11

DKD


2 Answers

Thanks for providing ideas to my question.Spending couple of hours in Google I found solution .

public void Test() {
    var data = new[] {
        new TestData { X = 1, Y = 2, Z = 3 }
    ,   new TestData { X = 2, Y = 4, Z = 6 }
    };
    var strColumns = "X,Z".Split(',');
    foreach (var item in data.Select(a => Projection(a, strColumns))) {
        Console.WriteLine("{0} {1}", item.X, item.Z);
    }
}
private static dynamic Projection(object a, IEnumerable<string> props) {
    if (a == null) {
        return null;
    }
    IDictionary<string,object> res = new ExpandoObject();
    var type = a.GetType();
    foreach (var pair in props.Select(n => new {
        Name = n
    ,   Property = type.GetProperty(n)})) {
        res[pair.Name] = pair.Property.GetValue(a, new object[0]);
    }
    return res;
}
class TestData {
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}
like image 103
DKD Avatar answered Sep 21 '22 05:09

DKD


I assume that the list of the columns may come from an external resource and change, I propose:

With reflection you could produce a list of FieldInfo that correspond to each Column, then loop over each item on the list and each FieldInfo and call GetValue on the data object.

like image 42
Wojtek Turowicz Avatar answered Sep 22 '22 05:09

Wojtek Turowicz