Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

list - Dynamic Column Name in LinQ

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...