一个列表可以包含多个等于最小值的元素(见下文)。
我编写的通用扩展方法.FindEveryIndex() 可以处理整数、字符串等,而且非常灵活,因为您可以将条件指定为 Lambda 表达式。
另一个优点是它返回一个包含所有匹配条件的索引的列表,而不仅仅是第一个元素。
关于您的问题:最小值可以返回为:
var lst = new List<int>() { 1, 2, 1, 3, 4, 1 }; // example list
var minimum = lst.Min(); // get the minumum value of lst
var idx = lst.FindEveryIndex(x => x == minimum); // finds all indices matching condition
Console.WriteLine($"Output: {String.Join(',', idx.ToArray())}"); // show list of indices
它将返回索引 0、2 和 5,因为 lst1 中的最小值是 1:
输出:0,2,5
示例 2:
void Main()
{
// working with list of integers
var lst1 = new List<int>() { 1, 2, 1, 3, 4, 1 };
lst1.FindEveryIndex(x => x==1).Dump("Find 1"); // finds indices: [0, 2, 5]
lst1.FindEveryIndex(x => x==2).Dump("Find 2"); // finds index: [1]
lst1.FindEveryIndex(x => x==9).Dump("Find 9"); // returns [-1]
// working with list of strings
var lst2 = new List<string>() { "A", "B", "A", "C", "D", "A"};
lst2.FindEveryIndex(x => x=="A").Dump("Find A"); // finds indices: [0, 2, 5]
lst2.FindEveryIndex(x => x=="B").Dump("Find B"); // finds index: [1]
lst2.FindEveryIndex(x => x=="X").Dump("Find X"); // returns [-1]
}
扩展类:
public static class Extension
{
// using System.Collections.Generic;
public static IEnumerable<int> FindEveryIndex<T>(this IEnumerable<T> items,
Predicate<T> predicate)
{
int index = 0; bool found = false;
foreach (var item in items)
{
if (predicate(item))
{
found = true; yield return index;
};
index++;
}
if (!found) yield return -1;
}
}
注意:将两段代码 sn-ps 复制到 LinqPad C# 程序中即可立即运行。
或者,使用DotNetFiddle在线运行它。