简体   繁体   English

获取字符串数组中匹配元素的所有索引

[英]Getting all indexes of matching elements in string array

I have this string array: 我有这个字符串数组:

string[] stringArray = { "fg v1", "ws v2", "sw v3", "sfd v2"  };
string value = "v2";

How to get back all indexes of all occurrences value in the array? 如何获取数组中所有出现值的所有索引?

so for this example we should get an array of int = [1,3] preferable without looping. 因此对于此示例,我们应该获得一个int = [1,3]的数组,而不需要循环。

You can use the LINQ Where extension method to filter, and Select to get the index: 您可以使用LINQ Where扩展方法进行过滤,然后Select以获取索引:

int[] indexesMatched = stringArray.Select((value, index) => new { Value = value, Index = index }
                                  .Where(x => x.Value.Contains("v2"))
                                  .Select(x => x.Index)
                                  .ToArray();

That's right. 那就对了。 There is no method in the Array -class or extension method in the Enumerable -class which returns all indexes for a given predicate. 有在没有方法Array -class在或扩展方法Enumerable -class返回所有索引对于给定的谓词。 So here is one: 所以这是一个:

public static IEnumerable<int> FindIndexes<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
    int index = 0;
    foreach (T item in items)
    {
        if (predicate(item))
        {
            yield return index;
        }

        index++;
    }
}

Here is your sample: 这是您的示例:

string[] stringArray = { "fg v1", "ws v2", "sw v3", "sfd v2" };
string value = "v2";

int[] allIndexes = stringArray.FindIndexes(s => s.Contains(value)).ToArray();

It uses deferred execution, so you don't need to consume all indexes if you don't want. 它使用延迟执行,因此如果不需要,您不需要消耗所有索引。

Linq approach Linq方法

string[] stringArray = { "fg v1", "ws v2", "sw v3", "sfd v2" };
string value = "v2";

int[] result = stringArray.Select((x, i) => x.Contains(value) ? i : -1)
                          .Where(x => x != -1)
                          .ToArray();

Same result with Select followed by Where: 与Select相同的结果,后跟Where:

var indexes = stringArray.Select((x,i) => x.Contains(searchStr)? i.ToString() : "")
                         .Where(x=> x!="" ).ToList();

Working example 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM