开发者

Returning Index in Enumerable Select

开发者 https://www.devze.com 2022-12-25 13:47 出处:网络
I have a List<MyClass> with 2 items which have a SequenceNumber property. If I use this code below the returned index is 0 not 1:

I have a List<MyClass> with 2 items which have a SequenceNumber property.

If I use this code below the returned index is 0 not 1:

var test = TrackingCollection
                .Where(x =>  x.SequenceNumber == 2)
                .Select((item, index) =>
                                    new
                                    {
                                         index, item.SequenceNumber
                                    });

Is this because that refers to 0 as the index in my new anonymous type or is it some zero index based weirdness that开发者_StackOverflow社区 I just need to increment.

What I'm after is to return the index in TrackingCollection where the sequence number is 2 or 887 or any other correct index in the original collection...


It sounds like your problem is filtering the list before indexing it. You need to filter after generating the index. Simply put the Where clause later:

var test = TrackingCollection 
            .Select((item, index) => 
                                new 
                                { 
                                     index, item.SequenceNumber 
                                })
            .Where(x =>  x.SequenceNumber == 2);


Why should not it be zero? C#'s collections indexes are zero-based by default.

0

精彩评论

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