Reputation: 1080
I'm querying objects in the database and was wondering how do I get the rank order of which it occurred. So I have something like:
var productRank = db.Products.OrderBy(i => i.WilsonScore);
So I want to take a list of products, order then by their score and get the row number of the product ID I choose. So let's say I get
ProductID|Score
12 0.99
23 0.95
34 0.93
I want to get the product who has an ID of 34 row number of the returned result. In this case, it would be 3. If I chose ID 12, it would be 1.
Upvotes: 4
Views: 3277
Reputation: 37540
You can get the index using Select...
var productRanks = db.Products.OrderByDescending(i => i.WilsonScore)
.Select((p, idx) => new { Rank = idx + 1, Product = p });
var product34Rank = productRanks
.Single(p => p.Product.ProductID == 34)
.Rank; // 3
Upvotes: 2