Bohuslav Sys
Bohuslav Sys

Reputation: 87

Difference between contains and contains<> in c#

I may be stupid, but what is the difference between contains and contains<> in VS whisper help? Sometimes I get both, sometimes only the one with <>.

They things is that I am trying to use contains in where as in some solutions found here on SO, but it throws error that I best overload method has some invalid arguments (them method is System.Linq.ParallelEnumerable.Contains<TSource>(...)).

My code is like this:

defaultDL = db.SomeEntity
                    .Where(dl => dl.Something == this.Something
                        && (dl.AllLocation == true || this.SomeOtherEntity.Select(loc => loc.Location).Contains(dl.Location)))
                    .ToList();

Upvotes: 4

Views: 1649

Answers (4)

Rohit Rohela
Rohit Rohela

Reputation: 422

It has the following basic difference.

  1. Contains is an Extension method while Contains is not.
  2. Contains retrun IEnumerable<T> while Contais return bool value and determines whether your item is present or not. In Contain you can pass deligates that based on condition will return IEnumerable<T>.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191037

There are many possibilities. But here are the most common.

I'm guessing SomeOtherEntity is a reference to an ICollection<T>. That is a standard method on ICollection that scans in memory for reference equality (depending on implementation). You can read about that here.

There also is the Contains<T> which comes from LINQ. It is an extension method. It works on IEnumerable<T> which ICollection<T> is derived from. You can read about this one here.

Upvotes: 0

Mikhail Tulubaev
Mikhail Tulubaev

Reputation: 4271

Linq has extension method Contains<>. When you are using it - you can enter type parameters, or not. If you are not enter - c# compiler will try to specify arguments implicitly.

Some other enumerable classes (e.g. List<>) implement own Contain method.

So, when IntelliSense suggest Contains<> method - it is an implementation from Linq; when Contains - it is own implementation of concrete class.

About difference in implementation. Own implementation of class seems to be faster, than Linq implementation, because Linq implementation is more abstract from endpoint class.

Upvotes: 1

Yura
Yura

Reputation: 2431

If you navigate to definition of System.Linq.Enumerable.Contains method, you will see that it is declared as generic extension method.

public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value);

The reason why sometimes it is called with <type> arguments, and sometimes not - is because most of the time compiler will analize it's arguments and determine type automatically. So under the hood, it will be rewritten to explicit generic call.

Like

someCollection.Contains(someValue);

actually is being compiled to

Enumerable.Contains<CollectionInnerType>(someCollection, someValue);

Upvotes: 4

Related Questions