Как отфильтровать коллекцию по любому свойству с отражением? - PullRequest
3 голосов
/ 18 ноября 2011

У меня есть коллекция 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 Ответ

4 голосов
/ 18 ноября 2011

Попробуйте это:

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

Хотя для больших коллекций это будет очень медленно

...