Help with Linq To Object

T

timor.super

Hi group,

here's my code :

public class ClassA
{
public List<ClassB> ClassB { get; set; }
}
public class ClassB
{
public int value;
}

static void Main()
{
List<ClassA> list = new List<ClassA>
{
new ClassA
{
ClassB = new List<ClassB>
{
new ClassB { value = 1 },
new ClassB { value = 2 },
}
},
new ClassA
{
ClassB = new List<ClassB>
{
new ClassB { value = 3 },
new ClassB { value = 4 },
}
}
};

IEnumerable<IEnumerable<ClassB>> a = list.Select(classA =>
classA.ClassB.Where(b => b.value == 3)).Select(b => b);
}

what I would like to do is to have all the ClassB with value == 3

But all I can optain is an IEnumerable<IEnumerable<ClassB>>.
I'm not able to get an <IEnumerable<ClassB>.

How can I do this, avoiding the foreach ?

Thanks for your answer
 
M

Martin Honnen

what I would like to do is to have all the ClassB with value == 3

But all I can optain is an IEnumerable<IEnumerable<ClassB>>.
I'm not able to get an <IEnumerable<ClassB>.

How can I do this, avoiding the foreach ?

Use SelectMany to flatten the nested hierarchy, as in the following example:

IEnumerable<ClassB> bs = list.SelectMany(a =>
a.ClassB).Where(b => b.value == 3);
 
T

timor.super

Oh yes,
Thanks, it's the operator that missed me.

Can it be written with the sugar syntax ?
 
M

Martin Honnen

Oh yes,
Thanks, it's the operator that missed me.

Can it be written with the sugar syntax ?

IEnumerable<ClassB> bs =
from a in list
from b in a.ClassB
where b.value == 3
select b;

should be the equivalent of the SelectMany.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top