How to select array index after Where clause using Linq? How to select array index after Where clause using Linq? arrays arrays

How to select array index after Where clause using Linq?


You could do it this way:

weekDays.Select((day, index) => new { Day = day, Index = index })        .Where(x => x.Day.Contains("s"))        .Select(x => x.Index)        .ToArray();

Not sure if this is optimal..


Patko's answer is the way to go in the general case.

Here are 2 more options:

// Idea only works with collections that can be accessed quickly by index.int[] indices = Enumerable.Range(0, weekDays.Length)                          .Where(index => weekDays[index].Contains("s"))                          .ToArray();

With MoreLinq:

// Similar to Patko's idea, except using a 'named' type.int[] indices = weekDays.AsSmartEnumerable()                        .Where(item => item.Value.Contains("s"))                        .Select(item => item.Index)                        .ToArray();


This should work:

weekDays.Where(a => a.Contains("s")).Select((a, i) => i).ToArray();