开发者

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

Ok, there is probably a bett开发者_如何学Goer 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!


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 });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜