user190560
user190560

Reputation: 3539

Indexing in Linq

Why do we use index in "where clause"? Is it an auto generated number ans starts from zero? Simple example would be really helpful.

var query =... Where((p,index)..)

Upvotes: 1

Views: 402

Answers (3)

LukeH
LukeH

Reputation: 269648

Yes, it is an auto-generated number that starts from zero.

Use it whenever you need access to the index in your query.

var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

var evenLetters = alphabet.Where((p, index) => (index % 2) == 1);
var oddLetters = alphabet.Where((p, index) => (index % 2) == 0);

Upvotes: 3

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68747

var oddElements = query.Where((p, index) => index % 2 == 1);

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82375

The index should refer to the index of the current item in the collection (the zero based iteration).

There is a simple example on this page.

Upvotes: 1

Related Questions