Linq按两个字段分组并取平均值 [英] Linq to group by two fields and average
问题描述
我有以下C#模型:
public class RawData
{
public int questionnaireId { get; set; }
public int coachNodeId { get; set; }
public int questionnaireNumber { get; set; }
public float score { get; set; }
}
public class AveragedData
{
public int coachNodeId { get; set; }
public int questionnaireNumber { get; set; }
public float averageScore { get; set; }
}
我有一个API端点,该端点从数据库返回数据,映射为List<RawData>
.值是这样的:
I have an API endpoint which is returning data from a database, mapped as List<RawData>
. The values are like this:
questionnaireId | coachNodeId | questionnaireNumber | score
1 | 30 | 1 | 2
2 | 40 | 1 | 3
3 | 30 | 2 | 1
4 | 30 | 3 | 4
5 | 40 | 2 | 5
6 | 40 | 1 | 5
7 | 30 | 1 | 1
8 | 30 | 1 | 2
9 | 40 | 1 | 2
10 | 30 | 2 | 4
在LINQ查询中,我现在要做的是对由coachNodeId
和questionnaireNumber
分组的score
值取平均值,并返回类型为AveragedData
的列表.
What I need to do now, in a LINQ query, is to average out the score
values grouped by coachNodeId
and questionnaireNumber
and return a list of type AveragedData
.
对以上示例数据进行平均和分组后返回的值应为:
The values returned by averaging and grouping the example data above, should be:
coachNodeId | questionnaireNumber | averageScore
30 | 1 | 1.66666666 (calculated by: (2 + 1 + 2) / 3))
30 | 2 | 2.5 (calculated by: (1 + 4) / 2))
30 | 3 | 4 (calculated by: (4 / 1))
40 | 1 | 3.33333333 (calculated by: (3 + 5 + 2) / 3))
40 | 2 | 5 (calculated by: (5 / 1))
我对LINQ不熟悉,因此很难将查询组合在一起,将查询按coachNodeId
和questionnaireNumber
分组并取平均分,返回类型为List<AveragedData>
的对象.有人可以建议如何做到这一点吗?
I'm not experienced with LINQ so am struggling to put together a query that groups by both coachNodeId
and questionnaireNumber
and averages the score, returning an object of type List<AveragedData>
. Could anyone suggest how to accomplish this?
非常感谢.
推荐答案
假设您有一个名为list
的List<RawData>
,那么您想要的是
assuming you have a List<RawData>
called list
, you are wanting:
var results = list.GroupBy(x => new
{
questionnaire = x.questionnaireId,
coach = x.coachNodeId
})
.Select(x => new AveragedData
{
coachNodeId = x.Key.coach,
questionnaireNumber = x.Key.questionnaire,
averageScore = x.Average(xx => xx.score)
})
.ToList();
进行分组,然后使用Select
以及LINQ的Average
将数据投影到您的类型.
Do the grouping, then use a Select
to project the data to your type, using LINQ's Average
as well.
这篇关于Linq按两个字段分组并取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!