[英]Linq Query using GroupBy() and Sum() and Returning Values not Grouped
When attempting to write a linq query to Group some Data and Sum it, i'm receiving the following error:尝试编写 linq 查询以对某些数据进行分组并对其进行求和时,我收到以下错误:
CS1061 'CM_Records' does not contain a definition for 'Sum' and no extension method 'Sum' accepting a first argument of type 'CM_Records' could be found CS1061“CM_Records”不包含“Sum”的定义,并且找不到接受“CM_Records”类型的第一个参数的扩展方法“Sum”
var results = (from r in CM_Records
join sub in CM_Records on r.Id equals sub.Id
select new {R = r, S = sub}
into joined
group joined by new
{
label = joined.R.ServiceDateTime.Value.Month + "/" + joined.R.ServiceDateTime.Value.Day + "/" + joined.R.ServiceDateTime.Value.Year,
joined.R.CategoryId
}
into grouped
select grouped.Select(g =>
new
{
grouped.Key.label,
grouped.Key.CategoryId,
Value = g.S.Sum(x => int32.Parse(x.Value)), //This is the line that fails
//Value = g.S.Value, //Uncomment this line and comment the line above to get the following output.
ServiceTime = Convert.ToDateTime(g.S.ServiceDateTime).ToShortTimeString()
})
)
.SelectMany(x => x);
I understand that Sum Requires the object to be IQueryable
, just not sure how to accomplish that in this this query without breaking something else.我知道 Sum 需要对象为IQueryable
,只是不确定如何在此查询中完成该查询而不破坏其他内容。 Keep in mind that this query is being set to variable and then used in conjunction to generate a JSON object in C#.请记住,此查询被设置为变量,然后结合使用以在 C# 中生成 JSON 对象。
Current Output without SUM:无 SUM 的电流输出:
Label Cat. Value ServiceTime
1/1/2017 439960 121 9:00 AM
1/1/2017 439960 131 5:00 PM
1/1/2017 439960 213 11:45 AM
1/1/2017 439960 210 10:20 AM
1/1/2017 439961 143 9:30 AM
1/1/2017 439994 92 9:30 AM
1/1/2019 439989 0 7:00 PM
1/1/2020 439968 172 7:00 PM
1/10/2018 439968 124 7:00 PM
1/10/2018 439969 120 7:00 PM
I need the above results to be Grouped by the Label Column and the Values summed.我需要将上述结果按标签列分组,并将值相加。
Try this query:试试这个查询:
var results = (from r in CM_Records
join sub in CM_Records on r.Id equals sub.Id
select new {R = r, S = sub}
into joined
group joined by new
{
label = joined.R.ServiceDateTime.Value.Month + "/" + joined.R.ServiceDateTime.Value.Day + "/" + joined.R.ServiceDateTime.Value.Year,
joined.R.CategoryId
}
into grouped
select new
{
grouped.Key.label,
grouped.Key.CategoryId,
Value = grouped.ToList().Select(x => x.S.value).Sum()
}).ToList();
Including the ServiceTime doesn't make much sense, unless you decide to select the max, min or something like that.包括 ServiceTime 没有多大意义,除非您决定选择最大值、最小值或类似的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.