我有这个字符串数组:
string[] stringArray = { "fg v1", "ws v2", "sw v3", "sfd v2" };
string value = "v2";
Run Code Online (Sandbox Code Playgroud)
如何获取数组中所有出现值的所有索引?
所以对于这个例子,我们应该得到一个不需要循环的preferred数组int = [1,3]
。
您可以使用 LINQWhere扩展方法来过滤并Select获取索引:
int[] indexesMatched = stringArray.Select((value, index) => new { Value = value, Index = index }
.Where(x => x.Value.Contains("v2"))
.Select(x => x.Index)
.ToArray();
Run Code Online (Sandbox Code Playgroud)