我想通过属性名称过滤类的集合作为字符串。假设我有一个名为Person的类,我有一个它的集合,IEnumerable或List,我想过滤这个集合,但我不知道确切的过滤器,我的意思是我不能使用:< / p>
person.Where(x => x.Id == 1);
让我举个例子。
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int YearOfBorn {get; set;}
}
现在我创建了一个类似的集合:
List<Person> p = new List<Person>();
现在我要过滤名字为Alex的所有人,但我想使用此功能过滤它:
public List<Person> Filter(string propertyName, string filterValue, List<Person> persons)
那么如果我想使用Linq或Lambda,我该如何过滤它?
由于
答案 0 :(得分:2)
从技术上讲,您可以尝试使用 Reflection :
using System.Reflection;
...
// T, IEnumerable<T> - let's generalize it a bit
public List<T> Filter<T>(string propertyName, string filterValue, IEnumerable<T> persons) {
if (null == persons)
throw new ArgumentNullException("persons");
else if (null == propertyName)
throw new ArgumentNullException("propertyName");
PropertyInfo info = typeof(T).GetProperty(propertyName);
if (null == info)
throw new ArgumentException($"Property {propertyName} hasn't been found.",
"propertyName");
// A bit complex, but in general case we have to think of
// 1. GetValue can be expensive, that's why we ensure it calls just once
// 2. GetValue as well as filterValue can be null
return persons
.Select(item => new {
value = item,
prop = info.GetValue(item),
})
.Where(item => null == filterValue
? item.prop == null
: item.prop != null && string.Equals(filterValue, item.prop.ToString()))
.Select(item => item.value)
.ToList();
}