我想以字符串的形式通过属性名筛选类的集合。假设我有一个名为Person的类,我有一个它的集合,或者是IEnumerable,或者是List,我想过滤这个集合,但是我不知道确切的过滤器,我的意思是我不能使用:
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,我如何过滤它呢?
谢谢
发布于 2017-05-18 07:49:16
从技术上讲,您可以尝试使用反射
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();
}https://stackoverflow.com/questions/44041476
复制相似问题