开发者

How to select array index after Where clause using 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(da开发者_运维技巧y => 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 ?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜