列出<T> .FindIndex多个结果?

Kes*_*dal 8 c#

比方说,我们有一个List

List<int> lst = new List<int>();
lst.Add(20);
lst.Add(10);
lst.Add(30);
lst.Add(10);
lst.Add(90);
Run Code Online (Sandbox Code Playgroud)

如果我需要得到第一个元素的索引,我将使用20

FindIndex()
Run Code Online (Sandbox Code Playgroud)

但是有一种方法可以用于多种结果吗?假设我想拥有数字10的元素索引.

我知道有一个方法FindAll(),但这给了我一个新的List insted索引.

最好的(?)方法是获取索引数组.

Mir*_*Mir 12

以下代码的最大缺点是它使用-1作为幻数,但是在索引的情况下它是无害的.

var indexes = lst.Select((element, index) => element == 10 ? index : -1).
    Where(i => i >= 0).
    ToArray();
Run Code Online (Sandbox Code Playgroud)


Tim*_*hyP 5

一种可能的解决方案是:

var indexes = lst.Select((item, index) => new { Item = item, Index = index })
                 .Where(v => v.Item == 10)
                 .Select(v => v.Index)
                 .ToArray();
Run Code Online (Sandbox Code Playgroud)

首先,选择所有项目及其索引,然后筛选项目,最后选择索引

更新:如果您想要封装我或者Eve的解决方案,您可以使用类似的东西

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你会使用类似的东西:

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();
Run Code Online (Sandbox Code Playgroud)