2

I have a list of objects which contains a list of other objects.

List<Parent> Ps;

Parent:

class Parent 
{
   List<Childs> Cs;
}

Is there a possibility to create with Linq a list of tuples of parents and childs?

Tuple<Parent, Child>
0

2 Answers 2

3

You can use Enumerable.SelectMany:

List<Tuple<Parent, Child>> parentChilds = Ps
    .SelectMany(p => p.Cs.Select(c => Tuple.Create(p, c)))
    .ToList();

This is equal to this:

var pcQuery = from parent in Ps
              from child in parent.Cs
              select Tuple.Create(parent, child);
List<Tuple<Parent, Child>> parentChilds = pcQuery.ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for including comprehension and lambda syntax
2
var tuples = from p in Ps from c in p.Cs select Tuple.Create(p, c);

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.