LINQ to find array indexes of a value

前端 未结 6 1010
轻奢々
轻奢々 2021-02-01 00:23

Assuming I have the following string array:

string[] str = new string[] {\"max\", \"min\", \"avg\", \"max\", \"avg\", \"min\"}

Is it possbile t

6条回答
  •  温柔的废话
    2021-02-01 01:20

    You can use the overload of Enumerable.Select that passes the index and then use Enumerable.Where on an anonymous type:

    List result = str.Select((s, index) => new { s, index })
                          .Where(x => x.s== "avg")
                          .Select(x => x.index)
                          .ToList();
    

    If you just want to find the first/last index, you have also the builtin methods List.IndexOf and List.LastIndexOf:

    int firstIndex = str.IndexOf("avg");
    int lastIndex = str.LastIndexOf("avg");
    

    (or you can use this overload that take a start index to specify the start position)

提交回复
热议问题