简体   繁体   中英

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?

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

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..

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();
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM