2010-08-13 21 views
1

这是一个原因请看我刚才的问题:在管理IEnumerable.GroupBy更有效的方式()

Looking for a better way to sort my List<T>

基本上,我有一个类似的情况下,我需要做一个.GroupBy()大约40个不同的领域。

最初的代码会使用一个巨大的switch语句,但我想知道是否有更好的方法。

我真正想要做的是一样的东西:

// not sure what the GroupBy selector function def should be...
Dictionary<PortfolioMapping, Func<Holding, ???>> groupByMappings;

,我可以通过像使用组:

myPortfolioHoldings.GroupBy(groupByMaping[frmGroupBySelector.SelectedColumn]);

什么是正确的方法去做这个?

回答

1

您应该能够按object

Dictionary<PortfolioMapping, Func<Holding, object>> groupByMappings; 

这只要你的映射函数返回工作之一:

  • 的实例内置类型(如数字或字符串)
  • 实现的对象IEquatable<T>
  • 执行对象EqualsGetHashCode正确
+0

谢谢Tim!将测试和确认,但看起来像我正在寻找。 – code4life 2010-08-13 16:06:51

0

那么,我个人的做法是建立lambda表达式,然后将最终表达式应用到列表中。

我使用了一些扩展方法来Linq.Expression这只是包装类似如下:

<System.Runtime.CompilerServices.Extension()> _ 
Public Function Compose(Of T)(ByVal first As Expressions.Expression(Of T), ByVal second As Expressions.Expression(Of T), ByVal merge As Func(Of Expressions.Expression, Expressions.Expression, Expressions.Expression)) As Expressions.Expression(Of T) 

    '' build parameter map (from parameters of second to parameters of first) 
    Dim map = first.Parameters.[Select](Function(f, i) New With {f, .s = second.Parameters(i)}).ToDictionary(Function(p) p.s, Function(p) p.f) 

    '' replace parameters in the second lambda expression with parameters from the first 
    Dim secondBody = ParameterRebinder.ReplaceParameters(map, second.Body) 

    '' applycomposition of lambda expression bodies to parameters from the first expression 
     Return Expressions.Expression.Lambda(Of T)(merge(first.Body, secondBody), first.Parameters) 
    End Function 

<System.Runtime.CompilerServices.Extension()> _ 
Public Function [And](Of T)(ByVal first As Expressions.Expression(Of Func(Of T, Boolean)), ByVal second As Expressions.Expression(Of Func(Of T, Boolean))) As Expressions.Expression(Of Func(Of T, Boolean)) 
    Return first.Compose(second, AddressOf Expressions.Expression.And) 
End Function 

然后你就可以建立查询是这样的:

Dim MyQuery as Linq.Expressions.Expression(Of System.Func(Of MyListDataType, Boolean)) 
Dim MyGroupingExpression as Linq.Expressions.Expression(Of System.Func(Of MyListDataType, Boolean)) 

Dim MyQuery = Function(x) x.SomeValue = SomeExpectedValue 
Select case SomeOtherVariable 
    Case Option1 
     Dim MyGroupingExpression = <blah> 
    Case Option2 
     Dim MyGroupingExpression = <blah> 
End Select 

Dim Results = MyList.Where(MyQuery.And(GroupingExpression)) 

这是你在做什么后?