[英]How to filter list of classes by property name?
我想通過屬性名稱將一個類的集合過濾為一個字符串。 假設我有一個名為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,該如何過濾呢?
謝謝
從技術上講,您可以嘗試使用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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.