将linq中的字符串聚合或连接到SQL查询(SQL Server)

ari*_*iel 9 c# vb.net aggregate linq-to-sql

给出一个像这样的表

ID | Name | City
1  | X    | Y
2  | Z    | Y
3  | W    | K
Run Code Online (Sandbox Code Playgroud)

我想产生一个像这样的结果

ID | Description
1  | Y (X, Z)
3  | K (W)
Run Code Online (Sandbox Code Playgroud)

我试过类似的东西

From C In Clients Group C By C.ID, C.City _
Into G = Group Select New With {.ID = ID, .Description = City & _
" (" & (From C In Clients Select C.Name).Aggregate(Function(X, Y) X & ", " & Y) & ")"}
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误"不支持查询运算符'聚合'." 也试过了

From C In Clients Group C By C.ID, C.City _
Into G = Group Select New With {.ID = ID, .Description = City & _
" (" & String.Join((From C In Clients Select C.Name).ToArray, ", ") & ")"}
Run Code Online (Sandbox Code Playgroud)

这给了我错误"没有支持的SQL转换"

那么,我该怎么做呢?

Sis*_*utl 23

我在C#中攻击它,它似乎给你想要的东西.我会把翻译留给VB给你.

var clients = from c in context.Clients 
              group c by c.City into cities 
              select new {
                  ID = cities.First().ID,
                  City = cities.Key, 
                  Names = string.Join(",", (from n in cities select n.Name).ToArray()) 
              };

foreach (var c in clients) {
    Console.WriteLine(string.Format("{0}| {1} ({2})", c.ID, c.City, c.Names));
}
Run Code Online (Sandbox Code Playgroud)