使用LINQ组合给定数据表列中的项

时间:2013-05-07 19:45:25

标签: c# linq

我有一个看起来像这样的数据表:

Id                                   | Title       | Month | Year |
ebdef240-abb7-4a82-9229-1ed37496da86 | Maths FT    | 1     | 2013 |
57504a66-4882-4794-a8b9-af0ead38dc70 | Maths FT    | 2     | 2013 |
57504a66-4882-4794-a8b9-af0ead38dc70 | Maths FT    | 2     | 2014 |
57504a66-4882-4794-a8b9-af0ead38dc70 | Maths FT    | 2     | 2015 |
ebdef239-abb7-4a82-9229-1ed37496da86 | English PT  | 1     | 2013 |
ebdef239-abb7-4a82-9229-1ed37496da86 | English PT  | 1     | 2014 |

但我希望它像这样安排:

Id                                   | Title       | Month | Years            |
ebdef240-abb7-4a82-9229-1ed37496da86 | Maths FT    | 1     | 2013             |
57504a66-4882-4794-a8b9-af0ead38dc70 | Maths FT    | 2     | 2013, 2014, 2015 |
ebdef239-abb7-4a82-9229-1ed37496da86 | English PT  | 1     | 2013, 2014       |

将它表示为列表可能更有意义。我试图这样做,但我很困惑a)如何结合年份(如上所述,和b)包括非分组字段,例如ID(还有其他字段,这只是其中的几个)为简单起见的列):

来自LINQPad:

var objectTable = new DataTable();
objectTable.Columns.Add("Title",typeof(string));
objectTable.Columns.Add("id",typeof(Guid));
objectTable.Columns.Add("Month",typeof(int));
objectTable.Columns.Add("Year",typeof(string));
objectTable.Rows.Add("Maths FT", "ebdef240-abb7-4a82-9229-1ed37496da86", 1, "2013");
objectTable.Rows.Add("Maths FT", "57504a66-4882-4794-a8b9-af0ead38dc70", 2, "2013");
objectTable.Rows.Add("Maths FT", "57504a66-4882-4794-a8b9-af0ead38dc70", 2, "2014");
objectTable.Rows.Add("Maths FT", "57504a66-4882-4794-a8b9-af0ead38dc70", 2, "2015");
objectTable.Rows.Add("English PT", "ebdef239-abb7-4a82-9229-1ed37496da86", 1, "2013");
objectTable.Rows.Add("English PT", "ebdef239-abb7-4a82-9229-1ed37496da86", 1, "2014");

var DataSort = from row in objectTable.AsEnumerable()
            group row by new {title = row.Field<string>("Title"), month = row.Field<int>("Month")} into grp
            select new
                {
                    Title = grp.Key.title,
                    Month = grp.Key.month,                  
                };
DataSort.Dump();

任何例子都会非常感激。

感谢。

2 个答案:

答案 0 :(得分:2)

也许:

var result = objectTable.AsEnumerable()
    .Select(r => new { Row = r, Title = r.Field<string>("Title"), Month = r.Field<int>("Month") })
    .GroupBy(x => new { x.Title, x.Month })
    .Select( g => new { 
        id = g.First().Row.Field<Guid>("id"), 
        g.Key.Title, 
        g.Key.Month, 
        Year = g.Select(x => x.Row.Field<string>("Year")).ToList()
    });

如果您希望string使用逗号分隔列表而不是List<string>年份组使用Year = string.Join(",", g.Select(x => x.Row.Field<string>("Year")))

顺便说一下,为什么一年是string而不是int

答案 1 :(得分:0)

这将是输出的LINQ语句

from o in objectTable
group o by new { o.Id, o.Month, o.Title } into g
select new {Id = g.Key.Id, Title = g.Key.Id, Month = g.Key.Month, Years= String.Join(" ", g.Select(x=>x.Year).ToArray()) };