如何通过具有反射的任何属性筛选集合
本文关键字:属性 筛选 集合 任何 反射的 何通过 | 更新日期: 2023-09-27 18:14:57
我有一个IEnumerable集合。我想创建这样的方法:
public IEnumerable<object> Try_Filter(IEnumerable<object> collection, string property_name, string value)
{
//If object has property with name property_name,
// return collection.Where(c => c.Property_name == value)
}
有可能吗?我正在使用c# 4.0。谢谢!
试试这个:
public IEnumerable<object> Try_Filter(IEnumerable<object> collection,
string property_name, string value)
{
var objTypeDictionary = new Dictionary<Type, PropertyInfo>();
var predicateFunc = new Func<Object, String, String, bool>((obj, propName, propValue) => {
var objType = obj.GetType();
PropertyInfo property = null;
if(!objTypeDictionary.ContainsKey(objType))
{
property = objType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(prop => prop.Name == propName);
objTypeDictionary[objType] = property;
} else {
property = objTypeDictionary[objType];
}
if(property != null && property.GetValue(obj, null).ToString() == propValue)
return true;
return false;
});
return collection.Where(obj => predicateFunc(obj, property_name, value));
}
测试:
class a
{
public string t { get; set;}
}
var lst = new List<Object> { new a() { t = "Hello" }, new a() { t = "HeTherello" }, new a() { t = "Hello" } };
var result = Try_Filter(lst, "t", "Hello");
result.Dump();
但是,对于大型集合