在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技术小趣屋。