Dynamic Column Name in LinQ

后端 未结 1 1766
傲寒
傲寒 2020-12-10 15:26

I am having a class Item.

class Item{
        public int Id { get; set; }
        public DateTime CreatedDate { get; set; } 
        public string Name { get         


        
1条回答
  •  心在旅途
    2020-12-10 16:17

    Easy, just select the property you need from the list:

    var items = new List();
    //get names
    var names = items.Select(x => x.Name);
    //get descriptions
    var descriptions = items.Select(x => x.Description);
    

    Update:

    You'll need a bit of reflection to do this:

    var names = items.Select(x => x.GetType().GetProperty("Name").GetValue(x));
    

    Throw this in a method for re-usability:

    public IEnumerable GetColumn(List items, string columnName)
    {
        var values = items.Select(x => x.GetType().GetProperty(columnName).GetValue(x));
        return values;
    }
    
    
    

    Of course this doesn't validate wether the column exists in the object. So it will throw a NullReferenceException when it doesn't. It returns an IEnumerable, so you'll have to call ToString() on each object afterwards to get the value or call the ToString() in the query right after GetValue(x):

    public IEnumerable GetColumn(List items, string columnName)
    {
        var values = items.Select(x => x.GetType().GetProperty(columnName).GetValue(x).ToString());
        return values;
    }
    

    Usage:

    var items = new List(); //fill it up
    var result = GetColumn(items, "Name");
    

    0 讨论(0)
    提交回复
    热议问题