Dynamic Column Name in LinQ

25,010

Easy, just select the property you need 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:

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<object> GetColumn(List<Item> 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<object>, 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<string> GetColumn(List<Item> items, string columnName)
{
    var values = items.Select(x => x.GetType().GetProperty(columnName).GetValue(x).ToString());
    return values;
}

Usage:

var items = new List<Item>(); //fill it up
var result = GetColumn(items, "Name");
Share:
25,010
user1120418
Author by

user1120418

Updated on August 01, 2022

Comments

  • user1120418
    user1120418 almost 2 years

    I am having a class Item.

    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 list of items based on dynamic column name. Suppose I want list of Names then Column Name is "Name" and result will be list of names If column name is Description, I need list of descriptions.

    How to do this with LinQ?

  • Marco
    Marco almost 10 years
    items should be of type List<string>, shouldn't it?
  • Abbas
    Abbas almost 10 years
    No, the class is Item so it should be a list of that type. names and descriptions will be an IEnumerable<string>.
  • Marco
    Marco almost 10 years
    Yeah you're right. Don't know what I interpreted in you code - Sorry
  • user1120418
    user1120418 almost 10 years
    Here you have written two queries. For retrieving names and second for descriptions. I need one query which is generalized.
  • user1120418
    user1120418 almost 10 years
    If column doesn't exists, it will give NullReferenceException. How to handle this exception?