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

时间:2010-08-06 19:32:10

标签: c# vb.net linq-to-sql aggregate

给出像

这样的表格
ID | Name | City
1  | X    | Y
2  | Z    | Y
3  | W    | K

我想生成像

这样的结果
ID | Description
1  | Y (X, Z)
3  | K (W)

我试过像

这样的东西
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) & ")"}

这给了我一个错误“不支持查询运算符'Aggregate'。” 也尝试了

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, ", ") & ")"}

这给了我错误“不支持翻译成SQL”

那么,我该怎么做呢?

2 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分:0)

错误意味着您在编写TSQL时无法在SQL Server上执行LINQ操作。

要实现您的目标,您必须尽可能多地选择/评估基础数据,然后在第二步中执行聚合。两步或两步以上的过程并不理想,但可以做到。