Dynamically build select list from linq to entities query

前端 未结 3 1703
挽巷
挽巷 2020-12-13 22:21

I\'m looking for a way to dynamically create a select list from a iQueryable object.

Concrete example, i want to do something like the following:

pub         


        
3条回答
  •  抹茶落季
    2020-12-13 23:25

    I believe this is what you need:

    var entities = new List();
    
    entities.Add(new User { Name = "First", Type = "TypeA" });
    entities.Add(new User { Name = "Second", Type = "TypeB" });
    
    string[] columns = { "Name", "Type" };
    
    var selectResult = new List();
    
    foreach (var columnID in columns)
    {
        selectResult.AddRange(entities.Select(e => e.GetType().GetProperty(columnID).GetValue(e, null).ToString()));
    }
    
    foreach (var result in selectResult)
    {
        Console.WriteLine(result);
    }
    

    This code outputs:

    • First
    • Second
    • TypeA
    • TypeB

    UPDATE (according to comments)

    // initialize alist of entities (User)
    var entities = new List();
    entities.Add(new User { Name = "First", Type = "TypeA", SomeOtherField="abc" });
    entities.Add(new User { Name = "Second", Type = "TypeB", SomeOtherField = "xyz" });
    
    // set the wanted fields
    string[] columns = { "Name", "Type" };
    
    // create a set of properties of the User class by the set of wanted fields
    var properties = typeof(User).GetProperties()
                            .Where(p => columns.Contains(p.Name))
                            .ToList();
    
    // Get it with a single select (by use of the Dynamic object)
    var selectResult = entities.Select(e =>
    {
        dynamic x = new ExpandoObject();
        var temp = x as IDictionary;
        foreach (var property in properties)
            temp.Add(property.Name, property.GetValue(e));
        return x;
    });
    
    // itterate the results
    foreach (var result in selectResult)
    {
        Console.WriteLine(result.Name);
        Console.WriteLine(result.Type);
    }
    

    This code outputs:

    • First
    • TypeA
    • Second
    • TypeB

提交回复
热议问题