【转载】C#中List集合使用Contains方法判断是否包含某个对象

在C#的List集合中,如果要查找List集合是否包含某一个值或者对象,如果不使用List集合类的扩展方法的话一般会使用for循环或者foreach遍历来查找,其实List集合类中的扩展方法Contain方法即可实现此功能,Contain方法的签名为bool Contains(T item),item代表具体需要判断的被包含对象。

例如有个List<int>的集合list1,内部存储10个数字,判断list1是否包含数字10可使用下列语句:

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

上述计算结果为isContain=true。

如果List集合是引用类型的对象的话,则是依据对象的引用地址是否相同来判断,如果被判断对象的引用地址不在List集合中,那即使这个对象的所有属性与List集合中的某个元素所有属性一致,返回结果也是为false。如下面这个例子:

   List<TestModel> testList = new List<ConsoleApplication1.TestModel>();
   TestModel testModel1 = new ConsoleApplication1.TestModel()
   {
       Index = 1,
       Name = "Index1"
   };
   TestModel testModel2 = new ConsoleApplication1.TestModel()
   {
       Index = 1,
       Name = "Index1"
   };

  testList.Add(testModel1);
  var isContain = testList.Contains(testModel2);

上述计算结果为:isContain=false

备注:原文转载自博主个人站IT技术小趣屋,原文链接为C#中List集合使用Contains方法判断是否包含某个对象_IT技术小趣屋

猜你喜欢

转载自www.cnblogs.com/xu-yi/p/11071148.html