0

I have an object model that contains several lists of other objects. I want to loop thought every object in the lists and execute a method on them. The method is called MyMethod and every object in the lists has this method in its class definition.

This is what I have:

public class MyObject
{
  public List<NestedObject1> ListNestedObject1 { get; set; }
  public List<NestedObject2> ListNestedObject2 { get; set; }

  public void ExecuteMethodsOfNestedObjectLists()
  {
    if (ListNestedObject1.Count > 0) { from a in ListNestedObject1 a.MyMethod();}
    if (ListNestedObject2.Count > 0) { from a in ListNestedObject2 a.MyMethod();}
  }
}

I'm looking to test the length of each list of nested object and execute MyMethod over each element. I know I could do a foreach loop but I want to see how to use linq syntax to keep it short.

How do I rewrite this to make it work?

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510

4 Answers4

3

So you're asking how to execute this method for every nested object?

ListNestedObject1.ForEach(obj => obj.MyMethod());
ListNestedObject2.ForEach(obj => obj.MyMethod()); 

Note: List.ForEach is not LINQ(although it has a similar appearance) and was introduced in .NET 2.0.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You should use a foreach loop. That's what it's for.

Linq is designed for querying data, and isn't designed to be used to cause side effects. It seems what you're looking for is a Linq ForEach extension method. Eric Lippert explains why this was intentionally omitted from the language in more detail if you are interested.

You are of course free to disregard these philosophical issues and write your own ForEach method.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

Instead of

 if (ListNestedObject1.Count > 0) { from a in ListNestedObject1 a.MyMethod(); }

Use

    if (ListNestedObject1.Count > 0)
    { 
        ListNestedObject1.Select(
        a=>
            { 
                a.MyMethod(); 
                return a;
            } 
    }

Replace query similarly for ListNestedObject2

Tilak
  • 30,108
  • 19
  • 83
  • 131
0

You can use the ForEach extension method from List<T>, which is really just the same as the foreach loop. Note that this is not available on IEnumerable<T>, and in general it is highly debated whether this should be used instead of a foreach loop.

MyObject.ListNestedObject1.ForEach(MyMethod);
MyObject.ListNestedObject2.ForEach(MyMethod);
goric
  • 11,491
  • 7
  • 53
  • 69