tags:

views:

67

answers:

3

Hi,

I have object A which contains multiple instances of object B, which in turn contains multiple instances of object C. I need to write a function which, given Object A needs search through instances of objects B and objects C and find a particular object C. How would I do this using LINQ?

+1  A: 

Assuming you want to get back the instance of ObjectB in ObjectA that contains the specified ObjectC:

public ObjectB FindObjectCContainer(ObjectA source, ObjectC value)
{
    return source.ObjectBs.Where(b => b.ObjectCs.Contains(value)).FirstOrDefault();
}

I assume here that ObjectA.ObjectBs and ObjectB.ObjectCs are both, at a minimum, an IEnumerable<ObjectB> and IEnumerable<ObjectC> (respectively).

Adam Robinson
+1  A: 

Given this object structure

class A
{
    public List<B> Bs { get; set; }
}

class B
{
    public List<C> Cs { get; set; }
}

class C
{
    public int D { get; set; }
}

And this initialization

A a = new A();
a.Bs = new List<B>();
a.Bs.Add(new B() { Cs = new List<C>() { new C() { D = 4 }, new C() { D = 5 } } });
a.Bs.Add(new B() { Cs = new List<C>() { new C() { D = 2 }, new C() { D = 3 } } });

You can find all instances of C where D equals 4 like this

var query = from b in a.Bs
            from c in b.Cs
            where c.D == 4
            select c;

The result type would be IEnumerable<C>. If you wanted or expected a single C, you could modify the query slightly.

C firstC = (from b in a.Bs
            from c in b.Cs
            where c.D == 4
            select c).FirstOrDefault();

Same queries in extension/lambda form

var allCs = a.Bs.SelectMany(b => b.Cs).Where(c => c.D == 4);
C firstC = a.Bs.SelectMany(b => b.Cs).FirstOrDefault(c => c.D == 4);
Anthony Pegram
A: 
        var objectC1 = new ObjectC() { id = 3 };
        var objectC2 = new ObjectC() { id = 1 };
        var objectB1 = new ObjectB() { objectCs = new List<ObjectC> { objectC1, objectC2 } };
        var objectBList = new List<ObjectB> {objectB1};
        var objectA = new ObjectA() { objectB = objectBList};

        var result = objectA.objectB.Select(b => b.objectCs.Where(c => c.id == 3));
DShultz
perfect! thanks.