What is the difference between Contains and Exists in List <T>?

I want to know what is different between Containsand Existsin List<T>?

They both can determine if the item is in List<T>.

But what is the difference between the two?

// Create a list of parts.
List<Part> parts = new List<Part>();

// Add parts to the list.
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;

// of the Part class, which checks the PartId for equality.
Console.WriteLine("\nContains: Part with Id=1444: {0}",
parts.Contains(new Part { PartId = 1444, PartName = "" }));

// Check if an item with Id 1444 exists.
Console.WriteLine("\nExists: Part with Id=1444: {0}",
                  parts.Exists(x => x.PartId == 1444)); 

// result
// Contains: Part with Id=1444: True 
// Exists: Part with Id=1444: True 
+5
source share
5 answers

The Exists and Contain methods look the same, but have different goals.

Exists : Determines whether List<T>elements contain elements that match the conditions specified by the specified predicate.

Contains : Determines if the item is in List<T>.

List<T>.Exists() , - ( ). "" - , () .

+12
  • Exists - List, IEnumerable .

  • - x => s.Exists(y => y == x.id) ( , , )

  • - Contains, Linq to Entities, Exists .

, ? , . , !

+5

Exists . .Equals , Part .

+2

, , List<T>.Exists MSDN, Contains -, . , , IComparable<T>, PartId, , - . , , List , IComparable<T>, .

List<T>.Exists , , - , - .

Spider_Says_hi , Contains LINQ , LINQ (LINQ to SQL, LINQ to Entities ..), LINQ List<T>.Exists IEnumerable<T>.Any.

+2

, Exists, . Contains EqualComparer , Equals. , , .

+1

Source: https://habr.com/ru/post/1612172/


All Articles