List <T> .FindIndex for multiple results?
let's say we have a list with
List<int> lst = new List<int>(); lst.Add(20); lst.Add(10); lst.Add(30); lst.Add(10); lst.Add(90); If I need to get the index of the first element, which is 20, I would use
FindIndex() But is there a method that can be used for multiple results? Say I would like to have an index of elements having the number 10.
I know there is a FindAll () method, but this gives me a new list containing indexes.
The best (?) Method would be to get an array of indices.
The biggest drawback of the following code is that it uses -1 as a magic number, but in the case of indices it is harmless.
var indexes = lst.Select((element, index) => element == 10 ? index : -1). Where(i => i >= 0). ToArray(); One possible solution is to:
var indexes = lst.Select((item, index) => new { Item = item, Index = index }) .Where(v => v.Item == 10) .Select(v => v.Index) .ToArray(); First you select all the elements and their index, then you filter the element and finally you select the indices
Update: If you want to encapsulate my or Eve solution, you can use something like
public static class ListExtener { public static List<int> FindAllIndexes<T>(this List<T> source, T value) { return source.Select((item, index) => new { Item = item, Index = index }) .Where(v => v.Item.Equals(value)) .Select(v => v.Index) .ToList(); } } And then you will use something like:
List<int> lst = new List<int>(); lst.Add(20); lst.Add(10); lst.Add(30); lst.Add(10); lst.Add(90); lst.FindAllIndexes(10) .ForEach(i => Console.WriteLine(i)); Console.ReadLine(); Just to give another solution:
Enumerable.Range(0, lst.Count).Where(i => lst[i] == 10) And, of course, this can be done using the extension method:
public static IEnumerable<int> FindAllIndices<T>(this IList<T> source, T value) { return Enumerable.Range(0, source.Count) .Where(i => EqualityComparer<T>.Default.Equals(source[i], value)); }