1. 程式人生 > 其它 >C# List集合中Exists方法判斷是否存在符合條件的元素物件

C# List集合中Exists方法判斷是否存在符合條件的元素物件

List集合中檢查元素是否存在有兩種方式:

(1).list.Contains():確定元素是否存在於列表中

(2).list.Exists():確定列表中是否存在指定謂詞的條件匹配的元素

Exists的使用

1.對List集合物件list1進行查詢判斷是否有元素物件的值為7

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

2.如果List集合中的元素是引用型別,還可以使用Exists方法根據集合中元素的某個屬性值為條件判斷。

我們需要對List集合物件testList進行查詢,判斷testList集合中是否存在物件的Index屬性為7的元素物件。

首先看下TestModel的定義:

public class TestModel
    {
         public int Index { set; get; }
 
        public string Name { set; get; }
    }

使用Exists方法的判斷語句書寫形式如下:

List<TestModel> testList = new List<ConsoleApplication1.TestModel>();
 
 if(testList.Exists(t => t.Name== "Tim"))
 {
    
 }