猿问

如何从 c# 中的列表中选择第二高的值?

我有一个列表List<int> myList = new List<int>() { 10, 20, 8, 20, 9, 5, 20, 10 };,我想选择第二高的值,在这种情况下10。我写了这段代码,它可以工作,但我想知道是否有更短更好的东西。


List<int> myList = new List<int>() { 10, 20, 8, 20, 9, 5, 20, 10 };

myList = myList.Distinct().ToList();

var descendingOrder = myList.OrderByDescending(i => i);

var sec = descendingOrder.Skip(1).First();


交互式爱情
浏览 213回答 4
4回答

慕的地8271018

你可以停止使用中间变量和ToList()var&nbsp;secondHighest&nbsp;=&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;myList &nbsp;&nbsp;&nbsp;&nbsp;.Distinct() &nbsp;&nbsp;&nbsp;&nbsp;.OrderByDescending(i&nbsp;=>&nbsp;i); &nbsp;&nbsp;&nbsp;&nbsp;.Skip(1) &nbsp;&nbsp;&nbsp;&nbsp;.First();这将与您的版本相同,但只需要一个语句而不是三个。我发现阅读代码列表要容易得多。每个 LINQ 方法都在它自己的行上调用,并且没有中间变量,尤其是那些发生变化的变量(myList被重新分配,这使得它更难理解)。

慕村225694

Dave建议在一个管道中执行所有操作确实非常好,因为它避免了:不必要的中间变量在中间步骤急切地创建新的集合对象减少混乱。更具可读性,即更容易看到发生了什么另一方面,就效率而言,最好对源列表执行两次遍历,而不是“排序”整个列表以获取第二项。var&nbsp;maximum&nbsp;=&nbsp;myList.Max(); var&nbsp;secondMaximum&nbsp;=&nbsp;myList.Where(x&nbsp;=>&nbsp;x&nbsp;<&nbsp;maximum).Max();

哆啦的时光机

它不是 LINQ-y,但它是 O(N) 且易于阅读:&nbsp; public static int TheSecondMax()&nbsp; {&nbsp; &nbsp; &nbsp; List<int> myList = new List<int>() { 10, 20, 8, 20, 9, 5, 20, 10 };&nbsp; &nbsp; &nbsp; int max = int.MinValue;&nbsp; &nbsp; &nbsp; int secondMax = int.MinValue;&nbsp; &nbsp; &nbsp; foreach (var item in myList)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (item > max)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = item;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (item > secondMax && item < max)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; secondMax = item;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return secondMax;&nbsp; }

慕尼黑的夜晚无繁华

我想我会为此避免使用 LINQ,而只使用标准的“循环遍历每个元素,如果电流高于最大值,则将电流最大值推到第二位,将当前值推到电流最大值”int sec = int.MinValue;for(int i =0, m= int.MinValue; i <list.Length; i++)&nbsp; if(list[i] > m){&nbsp; &nbsp; sec = m;&nbsp; &nbsp; m = list[i];&nbsp; }您给定的逻辑区分了这些值,因此即使有三个值为 20 的值,看起来 20 也不是列表中的第二高。这是通过 > 实现的。如果我使用 >= 则每 20 个将滚动变量,它的行为就好像没有区别如果您对性能感兴趣,请在包含几百万个条目的列表中对其进行测试,然后选择满足您对可读性与速度的胃口的一个
随时随地看视频慕课网APP
我要回答