在C#的List集合中,如果要查找List集合是否包含某一個值或者對象,如果不使用List集合類的擴展方法的話一般會使用for迴圈或者foreach遍歷來查找,其實List集合類中的擴展方法Contain方法即可實現此功能,Contain方法的簽名為bool Contains(T item),ite ...
在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技術小趣屋。