Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T>.FindIndex for multiple results?

Tags:

c#

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.

like image 653
Kesandal Avatar asked Jan 05 '13 17:01

Kesandal


2 Answers

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();
like image 166
Mir Avatar answered Oct 16 '22 09:10

Mir


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();
like image 5
TimothyP Avatar answered Oct 16 '22 07:10

TimothyP