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
首先看下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"))
{
}