Clean way to return array indices matching a condition using LINQ
I want to return all of the indices from an array where a condition is met. I've come up with
myarray
.Select((p,i) =>
{
if (SomeCondition(p)) return i;
else return -1;
})
.Where(p => p != -1);
I know I can write an exten开发者_如何学运维sion method or do it with a loop, but I was wondering if there was something built into LINQ that I'm unfamiliar with. Apologies if this is trivial
Personally, I'd go with this:
myarray
.Select((p, i) => new { Item = p, Index = i })
.Where(p => SomeCondition(p.Item))
.Select(p => p.Index);
When I read the text of the question and not the sample:
int[] data = { 1, 2, 5, 6, };
var results = Enumerable.Range(0, data.Length).Where(i => data[i] > 2);
// results = { 2, 3 }
Do you really need those -1
s ?
I would probably write an extension method, but if I chose not to, I would do this:
array
.Select((item, index) => SomeCondition(item) ? index : -1)
.Where(index => index != -1);
It's exactly what you are doing already, but less verbose since it uses the ternary if operator instead of the if
/else
block.
精彩评论