Sergio
Sergio

Reputation: 9917

Given a List of objects, how can I find the index of any particular object?

Ok, there is probably a better way of doing this, and if this is please let me know!

I have a List of Users (an entity framework entity within my system). Each User object has certain properties. I need to rank all users based on these properties one by one (who made the most sales etc etc)

At the moment I am thinking that the best way to do this is to reorder the List using LINQ's OrderBy extension method on the property that I am ranking on into a new list. Once this is done I should be able to get the position of the user within this newly ordered List, which will be a indication of their rank. (I know its going to get more complex when users have the same value for said properties)

The question is, how?

Thanks!

Upvotes: 0

Views: 130

Answers (1)

Bryan Watts
Bryan Watts

Reputation: 45445

var users = new List<User> { ... };

var userRanks = users
    .OrderBy(user => user.Prop1)
    .ThenBy(user => user.Prop2)
    .Select((user, index) => new { User = user, Rank = index + 1 });

Upvotes: 4

Related Questions