【转载】C#中List集合使用Exists方法判断是否存在符合条件的元素对象

在C#的List集合操作中,有时候需要根据条件判断List集合中是否存在符合条件的元素对象,此时就可以使用List集合的扩展方法Exists方法来实现,Exists方法的签名为bool Exists(Predicate<T> match),match代表条件方法表达式,一般使用Lambda表达式为多,通过Exists判断是否存在符合条件的元素对象比使用for循环或者foreach遍历查找更简便直接。

(1)对List<int>集合对象list1进行查找判断是否有元素对象的值为7

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

(2)如果List集合中的元素是引用类型,还可以使用Exists方法根据集合中元素的某个属性值为条件判断。

我们需要对List<TestModel>集合对象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>();
 var resultModel = testList.Exists(t => t.Index == 7);

 

 

posted @ 2019-06-16 09:31  江湖逍遥  阅读(27101)  评论(1编辑  收藏  举报