Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select array index after Where clause using Linq?

Tags:

arrays

c#

linq

Suppose I have the array string[] weekDays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; , and I want to find out the index of array elements containing 's'. How can I do this using Linq ?

I've tried int[] indexOfDaysContainingS = weekDays.Where(day => day.Contains("s")).Select((day, index) => index).ToArray();, but this returns 0,1,2 as presumably it's getting the index of the filtered IEnumberable<string> after the Where() clause instead. If I put the Select() first, then all I have is the index and can't filter by the days.

What do I need to change to make it work and return 1,2,3 instead ?

like image 783
Michael Low Avatar asked Nov 20 '10 10:11

Michael Low


1 Answers

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

like image 100
Patko Avatar answered Sep 20 '22 14:09

Patko