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"))
 {
    
 } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM