The question can be rephrased to "How do I get index of element in IEnumerable". Here is the answer: How to get index using LINQ?
Here is how to use it:
int rank = lstTeamSales.OrderBy(x => x.TotalSales).FindIndex(x => x.userID == currentUserID);
And this will be slightly more efficient than Select
based approaches.
Update
It appears .FindIndex is not supported for LINQ. Any idea how to implement that functionality?
I may have figured it out testing it now. I just added .ToList() after the ORderBy().
No-no-no-no! It kills the whole idea :( The idea is to add extension method FindIndex
to IEnumerable. And then use it. See example:
static class FindIndexEnumerableExtension
{
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items)
{
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
}
class YourClass
{
void YourMethod()
{
lstTeamSales.OrderBy(x => x.TotalSales).FindIndex(x => x.UserID == currentUserID);
}
}
After you define class FindIndexEnumerableExtension
with FindIndex
extension method, you can use this method anywhere in your code. All you need is just add using
directive with module where FindIndexEnumerableExtension
is defined. This is, basically, how LINQ works.
If you don't want to go with this solution then, at least, convert lstTeamSales to List before sorting it. And sort it using List<>.Sort()
method.