1

With Linq you can group and sum or group and count. Is it possible to group an concat strings?

Here is an example:

var list = (from x in Context.tblProduct
            group x by new { x.OrderNo, x.Color } into groupedByColorCode
            select new
                {
                    OrderNo = groupedByColorCode.Key.OrderNo,
                    ProductRef = groupedByColorCode.FirstOrDefault().ProductRef,
                    Color = groupedByColorCode.Key.Color,
                    Size = groupedByColorCode.Concat(bcc => bcc.Size).ToString(), // This line doesn't work
                    TotalQuantity = groupedByColorCode.Sum(bcc => bcc.OriQty).ToString()
                });

What should I write in place of

Size = groupedByColorCode.Concat(bcc => bcc.Size).ToString()

2 Answers 2

4

Simply use String.Join overload that accepts an IEnumerable<string>:

var size = String.Join("", groupedByColorCode.Select(bcc => bcc.Size));

Edit: Oh:I get it! I never ever use Linq for SQL queries, so I wasn't catching up with the problem. If this gets translated into SQL, there is no way you can do that on the database (if you're not on PostgreSQL or some other smart db and you don't want to mess with SQL itself). SQL can do Sum, Avg, etc, but no Concat (usually). You'll have to retrieve the colorcodes and join them after the roundtrip on the db, with the provided method.

Sign up to request clarification or add additional context in comments.

6 Comments

My var list is of type Lis<'a> 'a is anonymous type and correspond to my select New definition. When I add your solution into my select new the type change to ?. Yes to a question mark.
How are you inserting it? In my example I put a var which is not suitable for Linq, same for the ";" at the end of the line. Just put "Size = " as in your example and "," instead of ";".
Do keep in mind that this solution may not work if the provider doesn't translate the call to String.Join to an appropriate SQL instruction. You may need to complete your SQL query without the String.Join and then bring the results into memory before doing the join then.
@B413 Please don't edit answers with new questions. In any case, the problem was because the answer had a typo (missing closing bracket) which has now been fixed.
@Rob I didn't noticed the missing bracket. Thank you Rob.
|
0

You can also use aggregate as an alternative - although join (already suggested) is the most direct approach. Smink describes the process in his answer to a similar question:

Using Aggregate Queries

Although, as the other post points out, it can be much slower than stringbuilder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.