【问题标题】:LINQ query to Group and get SumLINQ 查询到 Group 并获取 Sum
【发布时间】:2017-09-23 03:06:26
【问题描述】:

我有以下查询,它连接了由 StationId 连接的 RailwayStation 对象和 ExpenditureData 对象的集合,我试图获取前 10 个 StationCargoCodes(Station 对象上的属性),并选择 ExpenditureCost 的总和作为顶部10 但我无法获得正确的语法:

var data = (from s in stations join e in expenditureData on s.stationId 
equals e.StationId 
orderby e.expenditureAmount descending 
select s)
.Sum(e => e.expenditureAmount)
.GroupBy(n => n.StationCargoCode)
.Take(10);

我需要什么 LINQ 来为此进行分组和求和?

【问题讨论】:

  • 不应该是.Sum(e => e.expenditureAmount)吗?
  • 总和是减少。它将返回一个金额并终止查询。可以将查询的公共部分封装成一个方法,然后分别调用.Sum和(GroupBy->Take)
  • 第二张海报是对的,你不能对 sum 的结果进行分组,那将是一个标量值。
  • 好吧,我很困惑。您是否需要前 10 个代码和前 10 个代码条目的总和?或者只是总和。
  • 顺便说一句,您可以在查询msdn.microsoft.com/en-us/library/bb384063.aspx中使用组子句

标签: c# linq


【解决方案1】:
var query = from s in stations
            join e in expenditureData
                on s.stationId equals e.StationId into se
            group se by new
            {
                s.StationCargoCode, ExpenditureCostSum = se.Sum(x => x.ExpenditureCost)
            } into g
            orderby g.Key.ExpenditureCostSum descending
            select g.Key;

var top10 = query.Take(10).ToList();

【讨论】:

  • @Novaterata 我不这么认为。我认为 OP 想要前 10 名StationCargoCode 以及他们的总和。获得前 10 个 StationCargoCode 不会很有用,因为它们只是代码。也许我弄错了,所以我们会看看OP怎么说。
  • 在这种情况下,这与您想要的非常接近。但不是在订购的地方订购,您需要在let sum = g.Sum(x => x.expenditureAmount) 然后order by sum 然后而不是select g 中提取总和@ 987654327@
  • @Theomax,你在说什么“其他对象”?据我们所知,只有一种对象类型,无论 ExpenditureData 是什么。你还有什么遗漏的吗?
  • @Theomax 查看我的编辑。它应该为您提供所需的一切。
  • @novaterata 不,你不是。您实际上非常有帮助并帮助我回答了这个问题
【解决方案2】:

我的朋友,你的优先级是错误的。 想一想,你得到前 10 名,然后进行求和操作。 上面的代码得到所有的总和,然后你取最后 10 个。 你的代码应该更像这样

var data = (from s in stations 
join e in expenditureData on s.stationId equals e.StationId 
orderby e.expenditureAmount descending 
select s)
.GroupBy(n => n.StationCargoCode) // you may need to do Select(x=> x.First()) if you want to have only distinct
.Take(10) // take the top 10 eg from 0 to 10
.Sum(e => e.expenditureAmount) // then Do sum on the result which will be the top 10

【讨论】:

  • 是否可以修改这个查询来选择前10个站点的支出金额之和?
  • 这不是在做什么吗?对不起,我没有注意到 orderby e.expenditureAmount 降序,您不需要 Reverse
猜你喜欢
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
相关资源
最近更新 更多