这是我上一个问题的延续:
寻找更好的方法对我的列表进行排序
基本上,我有类似的情况,我需要对大约 40 个不同的字段执行 .GroupBy() 。
原始代码会使用一个巨大的 switch 语句,但我想知道是否有更好的方法。
我真正想做的是:
// 不确定 GroupBy 选择器函数 def 应该是什么...
Dictionary>> groupByMappings;
我可以用它来分组,例如:
myPortfolioHoldings.GroupBy(groupByMaping[frmGroupBySelector.SelectedColumn]);
正确的方法是什么?
This is a segue to my previous question:
Looking for a better way to sort my List<T>
Basically, I have a similar situation where I need to do a .GroupBy() on about 40 different fields.
The original code would have used a giant switch statement, but I'd like to know if there's a better way to this.
What I'd really like to do is something like:
// not sure what the GroupBy selector function def should be...
Dictionary<PortfolioMapping, Func<Holding, ???>> groupByMappings;
which I can use to group by like:
myPortfolioHoldings.GroupBy(groupByMaping[frmGroupBySelector.SelectedColumn]);
What would be the correct way to go about this?
发布评论
评论(2)
您应该能够按
对象
进行分组:只要您的映射函数返回以下任一值,此功能就可以工作:
IEquatable 的对象;
Equals
和GetHashCode
的对象You should be able to group by
object
:This will work as long as your mapping functions return either:
IEquatable<T>
Equals
andGetHashCode
correctly嗯,我个人所做的就是构建 lambda 表达式,然后将最终表达式应用到列表中。
我对 Linq.Expression 使用一些扩展方法,它只包装如下所示的内容:
然后您可以构建如下查询:
这就是您想要的吗?
Well, what I personally do is build up lambda expressions and then applying the final expression to the list.
I use some extension method to Linq.Expression which just wrap something like the following:
And then you can build queries like this:
Is that what you're after?