Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何对一个属性进行聚合,同时对另一个属性进行求和?_C#_Linq_Aggregate - Fatal编程技术网

C# 如何对一个属性进行聚合,同时对另一个属性进行求和?

C# 如何对一个属性进行聚合,同时对另一个属性进行求和?,c#,linq,aggregate,C#,Linq,Aggregate,我有一个发票列表,每个记录由客户ID和金额组成。其目的是生成一个付款列表,其中每个客户的每笔付款都是唯一的(每个客户可能有多张发票),并将相关发票的金额总计 生成不同发票的列表(与客户ID相关)是一项非常重要的工作。问题是,我只有第一张发票的金额,而没有金额 List<Payment> distinct = invoices .GroupBy(invoice => invoice.CustomerId) .Select(group => group.First()

我有一个发票列表,每个记录由客户ID和金额组成。其目的是生成一个付款列表,其中每个客户的每笔付款都是唯一的(每个客户可能有多张发票),并将相关发票的金额总计

生成不同发票的列表(与客户ID相关)是一项非常重要的工作。问题是,我只有第一张发票的金额,而没有金额

List<Payment> distinct = invoices
  .GroupBy(invoice => invoice.CustomerId)
  .Select(group => group.First())
  .Select(invoice => new Payment
  {
    CustomerId = invoice.CustomerId,
    Total = invoice.Amount
  }).ToList();
List distinct=发票
.GroupBy(发票=>invoice.CustomerId)
.Select(group=>group.First())
.选择(发票=>新付款)
{
CustomerId=发票。CustomerId,
总计=发票金额
}).ToList();

是否有一个平滑的LINQ fu,或者我需要在我的列表中找到每一个吗?

如果你有这样的东西

Invoice[] invoices = new Invoice[3];

invoices[0] = new Invoice { Id = 1, Amount = 100 }; 
invoices[1] = new Invoice { Id = 1, Amount = 150 }; 
invoices[2] = new Invoice { Id = 2, Amount = 300 }; 
然后你就可以把你的目标定为

var results = from i in invoices
              group i by i.Id into g
              select new { Id = g.Key, TotalAmount = g.Sum(i => i.Amount)};

根据jmelosegui的回答:

List<Payment> distinct = invoices
   .GroupBy(c => c.CustomerId)
   .Select(c => new Payment
   {
     CustomerId = c.Key, 
     Total = c.Sum(x => x.Amount)
   }).ToList();
List distinct=发票
.GroupBy(c=>c.CustomerId)
.选择(c=>新付款
{
CustomerId=c.键,
总计=c.Sum(x=>x.Amount)
}).ToList();

如果您提供了示例输入和预期输出,以及到目前为止所取得的进展,那么帮助您会容易得多。@jmelosegui很棒,多亏了这两个方面。不过,我才意识到这是行不通的。所述问题的答案本身是有效的。遗憾的是,我得到了一个错误,即不能在LINQ to Entities查询中构造实体/复杂类型支付的实例。。。我假设这是一个与原始问题无关的问题,需要单独调查。