代码之家  ›  专栏  ›  技术社区  ›  code4life

更有效的管理方法IEnumerable.GroupBy组()

  •  1
  • code4life  · 技术社区  · 14 年前

    这是我上一个问题的一部分:

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

    基本上,我有一个类似的情况,我需要对大约40个不同的字段执行.GroupBy()。

    我真正想做的是:

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

    我可以用它来分组,比如:

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

    正确的方法是什么?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Tim Robinson    14 年前

    你应该能够分组 object :

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

    只要映射函数返回:

    • 内置类型的实例(例如数字或字符串)
    • IEquatable<T>
    • 实现的对象 Equals GetHashCode 正确地
        2
  •  0
  •   Basic    14 年前

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

    我用一些扩展方法Linq.表达式它只包含以下内容:

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

    这就是你想要的吗?