2

How would I search for a value within a List<t> inside another List<t>

i.e.

//FooInner Class
public class FooInner {

  public int FooInnerId { get; set; }
  public String FooValue { get; set; }

}   

//FooOuter Class
public class FooOuter {

  public int FooOuterId { get; set; }
  public List<FooInner> FooInnerCollection { get; set; }

}

If I just wanted to find a value in the outer class

// Working code

List<FooOuter> fooOuterCollection = GetSomeData(); 

var tmp = fooOuterCollection.Find( f => f.FooOuterId == 2 );

But what if I wanted the FooInner Object where FooOuterId == 2 and FooInnerCollection.FooInnerId == 4 (or contains depending how you look at it).

Hopefully that makes sense.

1

3 Answers 3

4
fooOuterCollection
    .Where(outer => outer.FooOuterID == 2)
    .SelectMany(outer => outer.FooInnerCollection)
    .FirstOrDefault(fooInner => fooInner.FooInnerId == 4);

First we filter the outer objects to only include those with Id == 2

Then we use SelectMany to flatten out the multiple InnerCollections that we may find

Finally we filter based on the inner Id == 4

1
3

You can get inner object like this-

var temp=  fooOuterCollection.Where(f => f.FooOuterId == 2)
            .SelectMany(f => f.FooInnerCollection)
            .FirstOrDefault(fi => fi.FooInnerId == 4));

If you need outer object, you need to use Any() extension method to see if inner list contains required element -

var temp = fooOuterCollection.FirstOrDefault(f => f.FooOuterId == 2 &&
               f.FooInnerCollection.Any(fi => fi.FooInnerId == 4);
5
  • 1
    this will return the outer object, not inner
    – Alex
    Jul 28, 2013 at 19:09
  • This is what Im looking for thank you. Actually Alex my question is incorrect not the answer but well spotted. If I have the outer object i can get to the inner one so its not a problem. :-) Jul 28, 2013 at 19:11
  • @William - Should i revert back then?
    – Rohit Vats
    Jul 28, 2013 at 19:13
  • The text and the code don't really share the same thought. "You need to use Any().." and than providing code without using it, looks kinda strange. Jul 28, 2013 at 19:14
  • No that's good. My problem is a little more complicated but those answers give my the correct path to solve my problem. Jul 28, 2013 at 19:27
0

You could just use LINQ's query syntax:

var results = from o in outerList
      where o.FooOuterId == 2
      from i in o.FooInnerCollection
      where i.FooInnerId == 4
      select i;
1
  • Will give the right results set but the asker wants a single object so you would need FirstOrDefault() or equivalent
    – Alex
    Jul 28, 2013 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.