C#中List集合使用Max()方法查找到最大值

发布日期:2019-11-24 作者:mi52.com 人气:

在C#的List集合操作中,有时候需要查找到List集合中的最大值,此时可以使用List集合的扩展方法Max方法,Max方法有2种形式,一种是不带任何参数的形式,适用于一些值类型变量的List集合,另一种是带Lambda表达式书写形式的,此方法可适用于获取List集合中某一个属性的最大值。


(1)不带任何参数的Max方法形式举例,程序调用形式如下:

 List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 var maxValue = list1.Max();

运算结果为:maxValue=10。


(2)带Lambda表达式书写形式的Max方法举例

我们需要获取List<TestModel>集合对象testList集合中对象属性Index的最大值,首先看下TestModel的定义:


   public class TestModel

    {

         public int Index { set; get; }

         public string Name { set; get; }

    }


获取testList集合中的所有对象的Index属性最大值可使用下列语句:

List<TestModel> testList = new List<ConsoleApplication1.TestModel>();

var max = testList.Max(t => t.Index);


返回顶部

拨打电话
首页