Aggregate or join strings in linq to sql query (SQ

2019-06-16 16:26发布

问题:

Given a table like

ID | Name | City
1  | X    | Y
2  | Z    | Y
3  | W    | K

I want to produce a result like

ID | Description
1  | Y (X, Z)
3  | K (W)

I tried something like

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

Which gave me an error "The query operator 'Aggregate' is not supported." Also tried

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

Which gave me the error "no supported translation to SQL"

So, how can i do this?

回答1:

I hacked this in C# and it seems to give what you want. I'll leave the translation to VB up to you.

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


回答2:

The error means that your LINQ operation cannot be performed on SQL Server in TSQL, as you've written it.

To achieve what you want, you'll have to select/evaluate as much of your base data as you can, and then perform the aggregation in a second step. A two-or-more step process isn't ideal, but it can be done.