Please explain System.Linq.Enumerable.Where(Func<T, int, bool> predicate)

浪子不回头ぞ 提交于 2019-12-22 08:33:54

问题


I can't make any sense of the MSDN documentation for this overload of the Where method that accepts a predicate that has two arguments where the int, supposedly, represents the index of the source element, whatever that means (I thought an enumerable was a sequence and you couldn't see further than the next item, much less do any indexing on it).

Can someone please explain how to use this overload and specifically what that int in the Func is for and how it is used?


回答1:


The int parameter represents the index of the current item within the current iteration. Each time you call one of the LINQ extension methods, you aren't in theory guaranteed to get the items returned in the same order, but you know they're all be returned once each and thus can be assigned indices. (Well, you are guaranteed if you know the query object is a List<T> or such, but not in general.)

Example:

var result1 = myEnumerable.Where((item, index) => index < 4);
var result2 = myEnumerable.Take(4);
// result1 and result2 are equivalent.



回答2:


You can't index an IEnumerable<T> in the same way you can an array, but you might be able to use the index to filter the list in some way, or possibly to index some data in another collection which will be used in the condition.

EDIT: As an example, to skip every other element you could use:

var results = sequence.Where((item, idx) => idx % 2 == 0);


来源:https://stackoverflow.com/questions/3288433/please-explain-system-linq-enumerable-wherefunct-int-bool-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!