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 that is 20 I would use
FindIndex()
But is there a method which can be used for multiple results? Let's say I would like to have the index of elements having the number 10.
I know there is a method FindAll() but this gives me a new List insted of the indexes.
The best(?) method would be to get an array of indexes.
The biggest downside of the following code is that it uses -1 as a magic number, but in case of indexes it's harmless.
var indexes = lst.Select((element, index) => element == 10 ? index : -1).
Where(i => i >= 0).
ToArray();
One possible solution is this:
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 items and their index, then you filter on the item and finally you select the indexes
Update: If you want to encapsulate either my or Eve's solution you could 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'd 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With