Tron Thomas
Tron Thomas

Reputation: 871

LINQ query to call instance method

I have written some code that has this form:

var  queryResult = from instance in someCollection
  where instance meets some criteria
  select instance;

foreach (InstanceType instance in queryResult.ToList()) {
    instance.SomeMethod();
}

This seems a bit redundant in that the query is iterating over the collection and then there is another iteration to invoke the method on all found instances. It would be nice to be able to invoke the instance method with in the query, rather than having to write an additional loop.

How could someone accomplish what the code above does with just a single query?

Upvotes: 0

Views: 320

Answers (3)

Jonathan
Jonathan

Reputation: 2358

Looks a little better. Im not sure of the actual number of iterations though.

foreach (var instance in someCollection.Where(instance meets some criteria))
{
    instance.SomeMethod();
}  

Upvotes: 1

Vikas Gupta
Vikas Gupta

Reputation: 4465

Just remove the .ToList() from your code.. and you'd be looping over the collection only once..

In general, it is advisable to not have side effects in your queries.. and methods like instance.SomeMethod() are typically side effects..

Apart from removing the ToList call (which is really the additional and redundant loop here), the code snippet looks fine to me..

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

You can use ForEach to call void methods:

someCollection
    .Where(instance => instance meets some criteria)
    .ToList()
    .ForEach(item => item.SomeMethod(param1, param2, ...)); // Use Foreach(SomeMethod) for methods w/no args

Upvotes: 2

Related Questions