在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