Linq Groupby问题没有总结

时间:2013-08-27 12:20:35

标签: c# linq

我遇到了一些问题,我正在尝试使用linq进行GroupBy,尽管它有效,但只有当我消除代码中的一个元素时它才有效。

nestedGroupedStocks = stkPositions.GroupBy(x => new { x.stockName,
                                     x.stockLongshort,x.stockIsin, x.stockPrice })
             .Select(y => new stockPos
             {
                 stockName = y.Key.stockName,
                 stockLongshort = y.Key.stockLongshort,
                 stockIsin = y.Key.stockIsin,
                 stockPrice = y.Key.stockPrice,
                 stockQuantity = y.Sum(x => x.stockQuantity)
             }).ToList();

以上代码将我的股票头寸和包含47个条目的列表中的结果分组,但它未能做的是对具有不同数量的重复股票进行汇总...

nestedGroupedStocks = stkPositions.GroupBy(x => new { x.stockName,
                         x.stockIsin, x.stockPrice })
             .Select(y => new stockPos
             {
                 stockName = y.Key.stockName,
                 stockIsin = y.Key.stockIsin,
                 stockPrice = y.Key.stockPrice,
                 stockQuantity = y.Sum(x => x.stockQuantity)
             }).ToList();

但是,如果我说“x.longshort”,那么我得到了理想的结果,总结了34个股票,但是列表中的所有长码元素都是空的......

它让我疯狂: - )

1 个答案:

答案 0 :(得分:2)

这部分

.GroupBy(x => new { x.stockName,x.stockLongshort,x.stockIsin, x.stockPrice })

是问题所在。您正尝试按新对象将元素分组为键,但x.stockLongshort很可能会更改列表中的每个元素,使GroupBy失败,除非名称和stockLongshort在两个元素中都匹配(至于其他两个领域,但我认为这些领域总是一样的。)

nestedGroupedStocks = stkPositions.GroupBy(x => x.stockName)
         .Select(y => new stockPos
         {
             stockName = y.First().stockName,
             stockLongshort = y.First().stockLongshort,
             stockIsin = y.First().stockIsin,
             stockPrice = y.First().stockPrice,
             stockQuantity = y.Sum(z => z.stockQuantity)
         }).ToList();

请注意,stockLongshort属性设置为等于组中第一个元素的值。如果这对你更有用,你可以将它设置为0.

更长的解释

GroupBy返回IEnumerable<IGrouping<TKey, TSource>>,即组的“set”(您可以enumarte),同一组中的每个元素共享相同的Key,您已使用lambda定义在论证中表达。

如果你将x.stockLongshort作为Key对象的属性,那将成为GroupBy所做评价的判别,因此,将两个不同的元素放在一起属于两个不同的群体。

相关问题