3

我有一个如下所示的数据表:

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();

任何示例将不胜感激。

谢谢。

4

2 回答 2

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"))).

顺便说一句,为什么是 astring而不是 a int

于 2013-05-07T19:57:01.350 回答
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()) };
于 2013-05-07T19:54:35.960 回答