locked
Multiple ForEachs, Possible To Avoid With LINQ? RRS feed

  • Question

  • I am wondering about getting rid of some nested foreach's in my code using LINQ. For example, assume the following code:

                      
      IEnumerable<MyObject1> MyObject1Collection = SomeCollection.Cast<MyObject1>()
                        foreach (MyObject1 obj1 in MyObject1Collection)
                        {
                            foreach (MyObject2 obj2 in MyObject1.MyObject2Collection)                           {                           
    
    if (MyObject2.IsFalse)
    {
    // Do Stuff
    }
    
    }
                        }
    Is there a better way to do this with LINQ?

    TIA!
    Friday, November 6, 2009 3:38 PM

Answers

  • There are two ways to do this: method syntax and query syntax:

    List<object> SomeCollection = new List<object>();

    var methodsyntax = SomeCollection.OfType<MyObject1>().SelectMany(x => x.MyObject2Collection).Where(x => x.IsFalse);

    var querysyntax = from obj1 in SomeCollection.OfType<MyObject1>()
                      from obj2 in obj1.MyObject2Collection
                      where obj2.IsFalse
                      select obj2;

    // use a foreach loop here.


    Coding Light - Illuminated Ideas and Algorithms in Software
    Coding Light WikiLinkedInForumsBrowser
    • Proposed as answer by Reed Copsey, JrMVP Friday, November 6, 2009 5:20 PM
    • Marked as answer by Harry Zhu Friday, November 13, 2009 2:02 AM
    Friday, November 6, 2009 3:44 PM