目前,我正在寻找一种方法来从可枚举对象中获取所有件数的总和,同时忽略重复项,所有这些都是使用方法语法进行的。就目前情况而言,我的代码可以工作,但我意识到这只是暂时的。稍后详细介绍。
让我们使用下面的类作为示例
internal class Piece
{
public int Count { get; set; }
public DateTime Date { get; set; }
public string Description { get; set; }
}
然后使用该类创建包含以下信息的列表
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);
这就是事情变得棘手的地方。如果要添加另一 block ,如下
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);
这样您就可以访问分组的所有关键属性。
这将为您的初始样本返回 85,如果您添加新样本,则返回 108。
关于c# - 使用多列进行分组,然后使用方法语法对特定列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57396809/