简体   繁体   English

如何在使用Linq的Where子句后选择数组索引?

[英]How to select array index after Where clause using Linq?

Suppose I have the array string[] weekDays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; 假设我有数组string[] weekDays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; , and I want to find out the index of array elements containing 's'. ,我想找出包含's'的数组元素的索引。 How can I do this using Linq ? 我怎么能用Linq做到这一点?

I've tried int[] indexOfDaysContainingS = weekDays.Where(day => day.Contains("s")).Select((day, index) => index).ToArray(); 我试过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. ,但这会返回0,1,2因为它可能是在Where()子句之后得到过滤后的IEnumberable<string>的索引。 If I put the Select() first, then all I have is the index and can't filter by the days. 如果我首先放置Select(),那么我所拥有的只是索引,不能按天来过滤。

What do I need to change to make it work and return 1,2,3 instead ? 我需要改变什么来使其工作并返回1,2,3

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: 这里有2个选项:

// 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 : 使用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();

这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM