c# index of array entries inside another array using LINQ

I have an array of strings:

string[] stringArray = {"aaa", "bbb", "ccc", "aaa", "ccc", "ddd"};

I would like to get all indexes of this array where a substring of these strings are inside another array:

string[] searchArray = {"a","b"};

The answer I would like to get is then:

index = {0,1,3};

A soultion for just one entry of the searchArray would be:

List<int> index = stringArray.Select((s, i) => new { i, s })
            .Where(t => t.s.Contains(searchArray[1]))
            .Select(t => t.i)
            .ToList();

A solution for all entries would be:

List<int> index = new List<int>();
foreach (string str in searchArray)
            index.AddRange(stringArray.Select((s, i) => new { i, s })
            .Where(t => t.s.Contains(str))
            .Select(t => t.i)
            .ToList());
index.Sort();

But out of curiosity, are there any solutions by just using one command in LINQ?

Jon Skeet
people
quotationmark

Yup, you just need Any to see if "any" of the target strings are contained in the array element:

List<int> index = stringArray
    .Select((Value, Index) => new { Value, Index })
    .Where(pair => searchArray.Any(target => pair.Value.Contains(target)))
    .Select(pair => pair.Index)
    .ToList();

people

See more on this question at Stackoverflow