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

18,515

Solution 1

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.

Solution 2

  1. Exists is a method of List, there is no such method on array or IEnumerable extensions.

  2. Correct syntax of usage of this method is x => s.Exists(y => y == x.id) (you should pass predicate, i.e. method which returns boolean)

  3. The difference is - Contains supported by Linq to Entities, Exists is not supported.

It looks like you got the code from here yes? Check out this thread here, as it asks a similar question. Hope it helps!

Solution 3

Exists can use any function. Contains depends on the implementation of .Equals in the element type and note that you had to create a new Part object to compare to the ones in the list.

Solution 4

The code you posted seems very similar to example code on the List<T>.Exists MSDN page, which shows quite clearly the complexity of using Contains for anything other than simple membership testing. Examine the code on that page and you'll see that they've implemented the IComparable<T> interface to allow for searching by PartId, which then means that you can't search by anything else. The good thing is that if you do just want to check if a List contains a particular object instance, and that object's type doesn't implement IComparable<T>, then it's fairly quick to do so.

List<T>.Exists on the other hand allows you to specify any evaluation you like - simple or complex - without locking your program into any particular set of rules for comparisons of that object.

As Spider_Says_hi mentioned in another answer, Contains is also present in LINQ and acts similarly, with the obvious proviso that it doesn't guarantee to behave identically in all LINQ variants (LINQ to SQL, LINQ to Entities, etc). The equivalent LINQ method for List<T>.Exists is IEnumerable<T>.Any.

Solution 5

In your example, in Exists method, you are defining the conditions for comparison. In the Contains method, it's determined based on the default EqualityComparer, unless you've overwritten the Equals method. So, you have to know what it's using to compare.

Share:
18,515

Related videos on Youtube

Vic
Author by

Vic

Learning by doing o:

Updated on June 14, 2022

Comments

  • Vic
    Vic almost 2 years

    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 
    
    • gregswiss
      gregswiss over 8 years
      possible duplicate, or at least related to: stackoverflow.com/questions/18651940/…
    • Jerry Bian
      Jerry Bian over 8 years
      Are you sure? The Contains should return False, since you created a new instance.
    • Vic
      Vic over 8 years
      Im sure :) This code are copy by MSDN , and I just edit some code
  • egmfrs
    egmfrs about 4 years
    This helped me with core 3.1 (upgraded from 2.1) - I had a breaking query because of EF changes.