Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's different between Contains and Exists in List<T>?

I want to know what's different between Contains and Exists in List<T> ?

They can both determine whether an element is in the List<T>.

But what's different between them?

// 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 
like image 984
Vic Avatar asked Oct 19 '15 01:10

Vic


People also ask

What is the difference between contains and any in Linq?

Contains takes an object, Any takes a predicate. So if you want to check for a specific condition, use Any . If you want to check for the existence of an element, use Contains .

How do you check a list contains an item in C#?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

How do you check if a list of strings contains a string in C#?

Contains() is a string method. This method is used to check whether the substring occurs within a given string or not. It returns the boolean value. If substring exists in string or value is the empty string (“”), then it returns True, otherwise returns False.

Is item in list C#?

Check if an item is in the C# list or not. The Contains method checks if the specified item already exists in the C# List. C# List<T> class provides methods and properties to create a list of objects (classes). The Contains method checks if the specified item is already exists in the List.


1 Answers

Exists and Contain methods look similar, but have different purposes.

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

Contains: Determines whether an element is in the List<T>.

List<T>.Exists() checks whether any of the items in the list satisfies a condition (specified as a predicate). The "predicate" is just a method that accepts the item to be tested and returns true (match) or false.

like image 57
Shweta Pathak Avatar answered Oct 04 '22 21:10

Shweta Pathak