使用多列分组,然后使用方法语法对特定列求和

Grouping using multiple columns, then summing a specific column using method syntax

目前我正在寻找一种方法来从可枚举中获取所有件数的总和,同时忽略重复项,所有这些都是在使用方法语法的同时进行的。就目前情况而言,我的代码可以正常工作,但我意识到这只是暂时的。稍后会详细介绍。

下面以class为例

internal class Piece
{
    public int Count { get; set; }
    public DateTime Date { get; set; }
    public string Description { get; set; }   
}

此 class 然后用于创建包含以下信息的列表

List<Piece> pieces = new List<Piece>
{
    new Piece(41,DateTime.Parse("2019-07-12"),"BB"),
    new Piece(41,DateTime.Parse("2019-07-12"),"BB"),
    new Piece(21,DateTime.Parse("2019-07-12"),"JP"),
    new Piece(23,DateTime.Parse("2019-07-14"),"AA")
};

为了求和,我得出了以下结论

int total = pieces.Where(x => x.Count > 0)
                  .GroupBy(x => x.Count, x => x.Date, 
                           (piece, date) => new { Count = piece,Date = date})
                  .Sum(x => x.Count);

这就是事情变得棘手的地方。如果再添加一块如下

new Piece(23,DateTime.Parse("2019-07-14"),"AB") 

由于我的分组方式,该部分将被忽略。这远非理想。

我发现了以下按多列分组的方法

GroupBy( x => new {x.Count,x.Date,x.Description})

但我找不到办法,所以我可以在这个分组上使用 Sum。这种使用 AnonymousType 的分组不允许我声明局部变量 (piece,date),因为我在之前的 GroupBy 中可以这样做(据我所知)。 现在,我拥有的代码可以解决问题,但情况不再如此只是时间问题。

一些额外的细节。

我正在使用 Razor 处理查询结果,但我无法控制从服务器获取的数据。使用linq操作数据基本上是我目前唯一的方法。

非常感谢任何帮助

对于计数你只需要这个查询:

int total = pieces
    .Where(x => x.Count > 0)
    .GroupBy(x => new { x.Count, x.Date, x.Description })
    .Sum(g => g.Key.Count);

因此您可以访问分组的所有关键属性。

这 returns 85 用于您的初始样品,如果您添加新样品则为 108。