Help with Linq To Object

  • Thread starter Thread starter timor.super
  • Start date Start date
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
 
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);
 
Oh yes,
Thanks, it's the operator that missed me.

Can it be written with the sugar syntax ?
 
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.
 
Back
Top