1

Recently I have a task which need to do as following description, my question is that is LINQ capable to do it?

Say I have a set of data, each consists of three columns: a(int),b(int),c(int)

What I want to do is to group these data by a and b, and for each distinct pair (a,b), store their corresponding c into separate list.

For example: If I have a set of data(a,b,c) {(1,3,5), (2,4,6), (1,3,7), (2,4,8)},

I want to split the data into two separate list, each contains c's value:

List 1 (a=1,b=3) : [5,7]

List 2 (a=2,b=4) : [6,8]

What I have tried is to group / order by the data by (a,b), and got a sorted list of data, I can of course use any loop to iterate the set of data and split them into several list, just wondering if there is a more beautiful solution, like using a single LINQ query?

Any suggetion is pleased! Thanks :)

1 Answer 1

1

Try this:

var result = data.GroupBy(x => new { x.a, x.b })
                 .Select(g => Tuple.Create
                 (
                     new List<int> { g.Key.a, g.Key.b }, 
                     new List<int>(g.Select(x => x.c))
                 )).ToList();

Here's the query expression equivalent:

var result = (from x in data
             group x by new { x.a, x.b } into g
             select Tuple.Create(
                 new List<int> { g.Key.a, g.Key.b }, 
                 new List<int>(g.Select(x => x.c)))).ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! Just want to ask, how can I do this in LINQ to entities? i.e. from s in data...
You are amazing, you got 666 rating now :)

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.