C# 如何通过任何具有反射的属性筛选集合?
我有无数的收藏品。我想创建这样的方法:C# 如何通过任何具有反射的属性筛选集合?,c#,reflection,c#-4.0,ienumerable,C#,Reflection,C# 4.0,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 =
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)
}
public IEnumerable Try\u过滤器(IEnumerable集合、字符串属性\u名称、字符串值)
{
//如果对象具有名为property\u name的属性,
//返回集合。其中(c=>c.Property\u 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));
}
public IEnumerable Try\u过滤器(IEnumerable集合,
字符串属性(名称、字符串值)
{
var objTypeDictionary=新字典();
var predictefunc=new Func((obj,propName,propValue)=>{
var objType=obj.GetType();
PropertyInfo属性=null;
if(!objTypeDictionary.ContainsKey(objType))
{
property=objType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
objTypeDictionary[objType]=属性;
}否则{
property=objTypeDictionary[objType];
}
if(property!=null&&property.GetValue(obj,null).ToString()=propValue)
返回true;
返回false;
});
返回集合。其中(obj=>predictefunc(obj,属性名称,值));
}
通过以下方式进行测试:
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();
a类
{
公共字符串t{get;set;}
}
var lst=new List{new a(){t=“Hello”},new a(){t=“HeTherello”},new a(){t=“Hello”};
var result=Try_Filter(lst,“t”,“Hello”);
result.Dump();
尽管如此,对于大型集合,这将非常缓慢,因此,请使用4-空格缩进,而不是8-空格缩进。代码窗口没有那么宽。@greatromul不用担心:)。另外,我忘记了我现在添加的空检查(如果您试图查找不存在的属性,它会崩溃)