过滤大量未知类型的集合

时间:2012-02-21 06:31:33

标签: c# linq c#-4.0 reflection

我想过滤一大堆未知类型的

List<object> _list;

我需要搜索多个属性的值,这些属性也在运行时传递

 List<SearchField> _searchFields;

SearchField基本上有一个字符串属性“ProprtyName”

    class SearchField
    {
        public string PropertyName{get; set;}
    }

我试过了

_list.Select(localItem => (from searchField in SearchFields
            let displayProperty = (from PropertyDescriptor property in properties
            where property.Name.ToLower() == searchField.FieldName.ToLower()
            select property).FirstOrDefault()
            where displayproperty != null
            let valueBinding = new BindingEvaluator<string>
            (
            new Binding(displayproperty.Name) 
            { 
                Mode = BindingMode.TwoWay, Source = localItem 
            })
           let obj = valueBinding.GetDynamicValue(localItem,true) ?? string.Empty
            select new IndexItem
            {
                SearchField = searchField,
                Text = obj,
                Item = localItem,
            }}).ToList()))

但是大型收藏会像20,000件物品一样需要8秒,这是完全不可接受的。请告诉我哪里做错了,我该怎么做才能优化它。

1 个答案:

答案 0 :(得分:2)

按字符串列名称排序:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering) {
    var type = typeof(T);
    var property = type.GetProperty(ordering);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
    return source.Provider.CreateQuery<T>(resultExp);
}

来自here

误解了这个问题。 您可能需要尝试Dynamic LINQ

 repository.Where( "@0 == @1", property.Name, value );