如何解决使用GroupBy和Sum进行Linq查询,并返回未分组的值
当尝试编写linq查询以对一些数据进行分组和求和时,我收到以下错误:
CS1061'CM_Records'不包含'Sum'的定义,并且没有 扩展方法'Sum'接受类型为'CM_Records'的第一个参数 可以找到
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);
我知道Sum要求对象为IQueryable
,只是不确定如何在此查询中完成该任务而不破坏其他内容。
请记住,此查询被设置为变量,然后结合使用以在C#中生成JSON对象。
无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
我需要将以上结果按“标签”列进行分组,并将值相加。
解决方法
尝试此查询:
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();
包括ServiceTime并没有多大意义,除非您决定选择max,min或类似的东西。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。