Reputation: 43
Can I write code like this with index
var someArray = new List<int>(){1,2,3,4,5};
var resultArray = someArray.Where((num, index) => index % 2 == 0);
like
var resultArray = from num in someArray...
Upvotes: 4
Views: 326
Reputation: 35803
The only way seems to be to hack around the problem:
var count = 0;
var resultArray = from num in someArray
let index = count++
where index % 2 == 0
select num;
Probably better to use the other syntax.
Upvotes: 1
Reputation: 63378
I suppose you are asking "can I use query expression syntax to get at the overload of Where
that provides the item index, in the way that I can using fluent method-chaining syntax".
The answer is no.
As seen in the docs for the no-index-parameter overload of Where
:
In query expression syntax, a
where
clause translates to an invocation ofWhere<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
.
Upvotes: 3
Reputation: 1039498
No, you cannot. There is no equivalent for the Where
extension method allowing you to use the index using LINQ syntax.
Upvotes: 2