简体   繁体   中英

When using the Linq methods .Any(<predicate>) and .All(<predicate>) on an IList, are the predicates applied to the list in a strict sequence?

I have a class SomeObject which has a function Evaluate() which returns a bool. If I had an IList<SomeObject> like this:

IList<SomeObject> parameters;
parameters.Add( objA );
parameters.Add( objC );
parameters.Add( objB );

And I apply a Linq expression like Any or All

var res = parameters.Any( p => p.Evaluate() );

what order would the predicate p.Evaluate() be evaluated in? Would it be

  • objA then objB then objC (assuming the SomeObject is sortable and objA < objB < objC )
  • objA then objC then objB (the order they were Add ed to the IList<> )

Or is the order of evaluation not something that can be relied upon?

LINQ operates on IEnumerable<T> instances, so the order in which operations are applied is pretty much the order the underlying enumerator returns them, by definition.

However, IList<T> does not have any guarantee in which order items are enumerated. In the vast majority of cases (and probably for all framework implementations of IList<T> ) it will be the index order of items in the list, but the interface doesn't seem to guarantee that, so an implementation could do whatever it wants.

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