c# - 使用 LINQ 查询获取索引值的集合

标签 c# .net arrays linq indexof

有更好的方法吗?

string[] s = {"zero", "one", "two", "three", "four", "five"};

var x = 
s
.Select((a,i) => new {Value = a, Index = i})
.Where(b => b.Value.StartsWith("t"))
.Select(c => c.Index);

即我正在寻找一种更有效或更优雅的方式来获取符合条件的项目的位置。

最佳答案

您可以轻松添加自己的扩展方法:

public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    int index=0;
    foreach (T element in source)
    {
        if (predicate(element))
        {
            yield return index;
        }
        index++;
    }
}

然后将其用于:

string[] s = {"zero", "one", "two", "three", "four", "five"};
var x = s.IndexesWhere(t => t.StartsWith("t"));

关于c# - 使用 LINQ 查询获取索引值的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/237377/

相关文章:

android - 带有额外变量的 gson 数组反序列化

javascript - 根据键从 JS 数组中分配变量值

c# - 理解和解决 K-Way 归并排序

c# - Kendo UI 网格中的内联编辑?

c# - Azure BlobBatchClient.DeleteBlobsAsync 始终返回 404 blob not found

C# 文本冒险音乐问题

c# - 垃圾收集器什么时候收集单例?

.net - .net 硬问题

c# - DataTable 未加载 SqlDataReader

java - java中的坐标验证