Dynamic column name in LinQ

I have a class.

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

I want to filter a list of items based on a dynamic column name. Suppose I need a list of names, then the column name is "Name", and the result is a list of names. If the column name is Description, I need a list of descriptions.

How to do it with LinQ?

+4
source share
1 answer

Just select the desired property from the list:

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

Update:

To do this, you need a little thought:

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

Throw this into a reuse method:

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

, , . NullReferenceException, . IEnumerable<object>, ToString() , ToString() GetValue(x):

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

:

var items = new List<Item>(); //fill it up
var result = GetColumn(items, "Name");
+7

Source: https://habr.com/ru/post/1548321/


All Articles