2013-08-27 101 views
0

我有点问题,因为我试图GroupBy使用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(); 

但是,如果我elimanate“x.longshort”然后我得到了想要的结果,34只个股总结出来的,但当时的列表中的所有longshort元素是空...

其驾驶我坚果:-)

+0

发布你的清单数据 –

回答

2

这部分

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

是问题所在。您尝试将新对象的元素作为关键字进行分组,但x.stockLongshort很可能会更改为列表中的每个元素,从而导致GroupBy失败,除非名称和stockLongshort在两个元素中都匹配(对于其他元素2个字段,但我认为这些字段总是相同的)。

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>>,即,“设定”(即可以enumarte)群组的,具有相同的组共享相同Key的每个元素,您已具有限定参数中的lambda表达式。

如果你把x.stockLongshort作为Key对象的属性,变成由GroupBy作出评价的判别,即,作为结果,把刚在两个不同的群体,物业不同的两个元素。

+0

谢谢。这是一种享受。现在我明白了为什么使用你的解释! Muchas Gracias – Timujin

+1

我已经添加了一些更多的文字,使外观更清晰,至少我希望如此:) – Save