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

转载于:https://www.50bit.cn/News/Index/6395.html

 

posted @ 2019-12-09 15:00  活着凑个人数  阅读(10712)  评论(0编辑  收藏  举报