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

在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);

 

C#编写的扫雷游戏源码(完整解决方案源码,可以直接编译运行):https://pan.baidu.com/s/1T4zVndyypzY9i9HsLiVtGg。提取码请关注博主公众号后,发送消息:扫雷源码。

posted @ 2019-06-23 13:19  江湖逍遥  阅读(24898)  评论(0编辑  收藏  举报