使用linq c#在值列表中查找第二个Max

时间:2014-04-04 20:38:56

标签: c# linq

如何使用LinqC#在值列表中找到第二个最大数字?

例如我有这个清单:

List<double> ListOfNums = new List<double> {1, 5, 7, -1, 4, 8};

有没有一种方法可以获得列表中第二个最大值7?

4 个答案:

答案 0 :(得分:16)

var secondMax = ListOfNums.OrderByDescending(r => r).Skip(1).FirstOrDefault();

OR

var secondMax = ListOfNums.OrderByDescending(r=> r).Take(2).LastOrDefault();

答案 1 :(得分:2)

只需将其转换为数组并获取第二个元素

 List<double> ListOfNums = new List<double> { 1, 5, 7, -1, 4, 8 };
 var  sndmax = ListOfNums.OrderByDescending(x => x).ToArray()[1]; 

答案 2 :(得分:1)

以下是使用List<T>.Sort方法的另一种方法:

ListOfNums.Sort();
var max = ListOfNums[1];

答案 3 :(得分:0)

对于更复杂的对象,可以使用以下解决方案。我发贴只是为某人可能需要一个想法。 例如,我们要从学生列表中找到学生获得的3.最高成绩。

这是为我们创建示例列表的基本类:

 public class Students
{
    public string StudentName { get; set; }
    public int GradePoint { get; set; }
    public int StudentId { get; set; }

    public List<Students> GetStudentRecords()
    {
        List<Students> stulist = new List<Students>();
        stulist.Add(new Students { StudentId = 1, StudentName = " Joseph ", GradePoint = 800 });
        stulist.Add(new Students { StudentId = 2, StudentName = "Alex", GradePoint = 458 });
        stulist.Add(new Students { StudentId = 3, StudentName = "Harris", GradePoint = 900 });
        stulist.Add(new Students { StudentId = 4, StudentName = "Taylor", GradePoint = 900 });
        stulist.Add(new Students { StudentId = 5, StudentName = "Smith", GradePoint = 458 });
        stulist.Add(new Students { StudentId = 6, StudentName = "Natasa", GradePoint = 700 });
        stulist.Add(new Students { StudentId = 7, StudentName = "David", GradePoint = 750 });
        stulist.Add(new Students { StudentId = 8, StudentName = "Harry", GradePoint = 700 });
        stulist.Add(new Students { StudentId = 9, StudentName = "Nicolash", GradePoint = 597 });
        stulist.Add(new Students { StudentId = 10, StudentName = "Jenny", GradePoint = 750 });
        return stulist;
    }
}

我们调用列表并编写输出:

  class Program
  {
    static void Main(string[] args)
    {
        var students = new Students();
        students.GetStudentRecords()
           .GroupBy(grp => grp.GradePoint)
           .OrderByDescending(x => x.Key).Skip(2)
           .Take(1)
           .SelectMany(s => s)
           .ToList()
           .ForEach(p => 
           Console.WriteLine($"Id : {p.StudentId}, Name : {p.StudentName}, achieved Grade Point : {p.GradePoint} "));
    }
  }

这是输出:

  

Id:7,姓名:David,已达到成绩点:750

     

编号:10,姓名:珍妮,得分:750