Linq to group by two fields and average

后端 未结 2 1834
情歌与酒
情歌与酒 2021-01-26 02:16

I have the following C# models:

public class RawData
{
    public int questionnaireId { get; set; }

    public int coachNodeId { get; set; }

    public int ques         


        
2条回答
  •  死守一世寂寞
    2021-01-26 02:47

    assuming you have a List 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();
    

    Do the grouping, then use a Select to project the data to your type, using LINQ's Average as well.

提交回复
热议问题