使用LINQ将具有相同值的行分组到列中

时间:2016-09-16 13:12:20

标签: c# .net database linq

我有 LINQ 查询,结果如下。

Student  Subject    Mark 
Adam     English    80
Adam     Math       70
Adam     Science    60
Moses    English    95
Moses    Science    75

现在我想要的就是将其转换为

Student English Math    Science
Adam    80      70      60
Moses   95              75

注意:主题数量不固定。

3 个答案:

答案 0 :(得分:2)

如果主题已知且已修复,您可以使用:

var query = db.StudentMarks
    .GroupBy(x => x.Student)
    .Select(g => new {
        Student = g.Key,
        English = g.Where(x => x.Subject == "English").Sum(x=> x.Mark),
        Math    = g.Where(x => x.Subject == "Math").Sum(x=> x.Mark),
        Science = g.Where(x => x.Subject == "Science").Sum(x=> x.Mark),
    });

答案 1 :(得分:1)

尝试这样的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable sourceTable = new DataTable();
            sourceTable.Columns.Add("Student", typeof(string));
            sourceTable.Columns.Add("Subject", typeof(string));
            sourceTable.Columns.Add("Mark", typeof(int));

            sourceTable.Rows.Add(new object[] { "Adam","English", 80});
            sourceTable.Rows.Add(new object[] { "Adam","Math", 70});
            sourceTable.Rows.Add(new object[] { "Adam","Science", 60});
            sourceTable.Rows.Add(new object[] { "Moses","English", 95});
            sourceTable.Rows.Add(new object[] { "Moses","Science", 75});

            List<string> subjects = sourceTable.AsEnumerable().Select(x => x.Field<string>("Subject")).Distinct().ToList();
            DataTable pivotTable = new DataTable();
            pivotTable.Columns.Add("Student", typeof(string));
            foreach(string subject in subjects)
            {
                pivotTable.Columns.Add(subject, typeof(int));
            }
            var students = sourceTable.AsEnumerable()
                .GroupBy(x => x.Field<string>("Student")).ToList();

            foreach (var student in students)
            {
                DataRow newRow = pivotTable.Rows.Add();
                newRow["Student"] = student.Key;
                foreach (DataRow row in student)
                {
                    newRow[row.Field<string>("Subject")] = row.Field<int>("Mark"); 
                }

            }
        }
    }
}

enter image description here

答案 2 :(得分:0)

如果您不知道会有多少科目,您可以将信息整理成嵌套词典,如下所示:

undefined