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

本文关键字:数据表 LINQ 组合 使用 | 更新日期: 2023-09-27 18:12:26

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

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

请举个例子。

谢谢。

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

可能:

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 ?

这将是您输出的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()) };