Skip to main content
 首页 » 编程设计

c#之如何使用 LINQ 从列表中获取索引

2024年02月13日11birdshome

我有一个列表,我正在填充一个团队的总销售额。

lstTeamSales.OrderBy(x => x.TotalSales); 

此列表有一个 int userID 和一个 decimal totalSales。

我按 totalSales 订购。那时我怎样才能确定登录人的等级?

我知道我可以将通过他的用户 ID 登录的人与列表中的用户 ID 进行比较。如果他在销售额中排名第三,我需要返回他排名的整数,即排名 3。

请您参考如下方法:

问题可以改写为“如何获取 IEnumerable 中元素的索引”。这是答案:How to get index using LINQ? 下面是如何使用它:

int rank = lstTeamSales.OrderBy(x => x.TotalSales).FindIndex(x => x.userID == currentUserID); 

这会比 Select 稍微高效一点基于方法。

更新

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

不不不!它扼杀了整个想法:( 这个想法是将 extension method FindIndex 添加到 IEnumerable。然后使用它。参见示例:

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

定义类之后 FindIndexEnumerableExtension与 FindIndex扩展方法,您可以在代码中的任何位置使用此方法。您只需要添加 using带有模块的指令 where FindIndexEnumerableExtension被定义为。这基本上就是 LINQ 的工作原理。

如果您不想使用此解决方案,那么至少在排序之前将 lstTeamSales 转换为 List。并使用 List<>.Sort() 对其进行排序方法。