1

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.

4 Answers 4

5

You can use the LINQ Where extension method to filter, and Select to get the index:

int[] indexesMatched = stringArray.Select((value, index) => new { Value = value, Index = index }
                                  .Where(x => x.Value.Contains("v2"))
                                  .Select(x => x.Index)
                                  .ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks! I had no clue that the .Select() method had an overload which supported index in the selector too: Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
4

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

Comments

2

Linq approach

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

1 Comment

You could use SelectMany instead of Select, and skip the Where.
1

Same result with Select followed by Where:

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

Working example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.