如何使用反射过滤任何属性的集合?

时间:2011-11-18 00:37:00

标签: c# reflection c#-4.0 ienumerable

我有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。 谢谢!

1 个答案:

答案 0 :(得分:4)

试试这个:

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();

虽然这对于大型集合来说非常慢