gpt4 book ai didi

c# - 获取 List 中最小值索引的快速/有效方法?

转载 作者:太空狗 更新时间:2023-10-29 17:40:22 28 4
gpt4 key购买 nike

有没有比这更有效/更快地找到最小值索引的方法?

int minimumValueIndex = List.IndexOf(List.Min());

最佳答案

是的,您可以通过构建自定义 Min() 扩展来消除 List.IndexOf() 的开销。 (实际上,Enumerable.Min() 应该有一个扩展,可以按键选择原始元素,而不是选择转换。在这种情况下,这种疏忽特别痛苦。)

public static int IndexOfMin(this IList<int> self)
{
if (self == null) {
throw new ArgumentNullException("self");
}

if (self.Count == 0) {
throw new ArgumentException("List is empty.", "self");
}

int min = self[0];
int minIndex = 0;

for (int i = 1; i < self.Count; ++i) {
if (self[i] < min) {
min = self[i];
minIndex = i;
}
}

return minIndex;
}

关于c# - 获取 List<T> 中最小值索引的快速/有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323386/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com