Linq to group by two fields and average

后端 未结 2 1830
情歌与酒
情歌与酒 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:26

    Try following :

                DataTable dt = new DataTable();
                dt.Columns.Add("questionnaireId", typeof(int));
                dt.Columns.Add("coachNodeId", typeof(int));
                dt.Columns.Add("questionnaireNumber", typeof(int));
                dt.Columns .Add("score", typeof(int));
    
                dt.Rows.Add(new object[] {1,30, 1, 2});
                dt.Rows.Add(new object[] {2,40, 1, 3});
                dt.Rows.Add(new object[] {3,30, 2, 1});
                dt.Rows.Add(new object[] {4,30, 3, 4});
                dt.Rows.Add(new object[] {5,40, 2, 5});
                dt.Rows.Add(new object[] {6,40, 1, 5});
                dt.Rows.Add(new object[] {7,30, 1, 1});
                dt.Rows.Add(new object[] {8,30, 1, 2});
                dt.Rows.Add(new object[] {9,40, 1, 2});
                dt.Rows.Add(new object[] {10,30, 2, 4});
    
                var averages = dt.AsEnumerable()
                    .GroupBy(x => new { coachNodeId = x.Field("coachNodeId"), questionnaireNumber = x.Field("questionnaireNumber") })
                    .Select(x => new { coachNodeId = x.Key.coachNodeId, questionnaireNumber = x.Key.questionnaireNumber, average = x.Average(y => y.Field("score")) })
                    .ToList();
    

提交回复
热议问题