views:

194

answers:

2

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 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...

+4  A: 

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);
Gabe
A: 

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

Andrey