2012-02-21 68 views
0

的我想過濾收集了大量的未知類型的篩選大量收集未知類型

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

反射很慢...... nuff說:)。 – Asken 2012-02-21 06:34:25

+0

'_searchFields'和'properties'集合的大小是多少? – penartur 2012-02-21 06:36:01

+0

大小更像20,000個項目 – gaurawerma 2012-02-21 06:38:36

回答

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); 
+0

如何使其工作? – gaurawerma 2012-02-21 06:56:42

+0

yourCollection.OrderBy(「PropertyName」)。ToList() – 2012-02-21 06:57:57

+0

但我有多個屬性需要搜索。 – gaurawerma 2012-02-21 07:00:30