开发者

Difference between List.All() and List.TrueForAll()

Is there a practical difference between .All() and .TrueForAll() when operating on a List? I know that .All() is part of IEnumerable, so why add .TrueForAll()开发者_JAVA技巧?


From the docs for List<T>.TrueForAll:

Supported in: 4, 3.5, 3.0, 2.0

So it was added before Enumerable.All.

The same is true for a bunch of other List<T> methods which work in a similar way to their LINQ counterparts. Note that ConvertAll is somewhat different, in that it has the advantage of knowing that it's working on a List<T> and creating a List<TResult>, so it gets to preallocate whatever it needs.


TrueForAll existed in .NET 2.0, before LINQ was in .NET 3.5.

See: http://msdn.microsoft.com/en-us/library/kdxe4x4w(v=VS.80).aspx


TrueForAll appears to be specific to List, while All is part of LINQ.

My guess is that the former dates back to the .NET 2 days, while the latter is new in .NET 3.5.


Sorry for digging this out, but I came across this question and have seen that the actual question about differences is not properly answered.

The differences are:

  1. The IEnumerable.All() extension method does an additional check for the extended object (in case it is null, it throws an exception).
  2. IEnumerable.All() may not check elements in order. In theory, it would be allowed by specification to have the items to check in a different order every call. List.TrueForAll() specifies in the documentation that it will always be in the order of the list.

The second point is because Enumerable.All must use a foreach or the MoveNext() method to iterate over the items, while List.TrueForAll() internally uses a for loop with list indices.

However, you can be pretty sure that also the foreach / MoveNext() approach will return the elements in the order of the list entries because a lot of programs expect that and would break if this would be changed in the future.

From a performance point of view, List.TrueForAll() should be faster because it has one check less and for on a list is cheaper than foreach. However, usually the compiler does a good job and optimizes here a lot, so that there will probably (almost) no difference measurable in the end.

Conclusion: List.TrueForAll() is the better choice in theory. But practically it makes no difference.


Basically, because this method existed before Linq did. TrueForAll on a List originated in Framework 2.0.


TrueForAll is not an extension method and in the framework from version 2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜