HaibaraAi
HaibaraAi

Reputation: 197

What difference between the Queryable.Contains method and the List<T>.Contains method in C#?

List<A> list=new List<A>();
var a=new A();
list.Add(a);
list.Contains(a);
list.Contains<A>(a);

What difference between this two cases? Why exists two method?

Upvotes: 1

Views: 962

Answers (3)

PMV
PMV

Reputation: 2128

There is no difference in this case between List.Contains (which is the implementation of ICollection.Contains) and Enumerable.Contains - in the case where the enumerable is a collection, IEnumerable.Contains simply invokes ICollection.Contains.

The reasoning there is that some collections - such as SortedSet - can implement a Contains method that operates at better than O(n) time. For non-collection types of Enumerable, IEnumerable.Contains will do a linear search over the enumeration.

There is also Queryable.Contains, but that's different - List isn't a queryable. Queryable.Contains can build this into a query expression which can be translated (for example, into SQL). Queryable and Enumerable extension methods are very different under the hood.

Upvotes: 2

Pavan Chandaka
Pavan Chandaka

Reputation: 12731

The algorithmic complexity of "LIST.contains" is O(n) always.

Where as "Queryable.contains" complexity depends on the collection implemented. For example, if underlying collection is "Hashset", then the algorithmic complexity is O(1).

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

If you ask about difference in its functionality, then there is actually none.

List.Contains() is a part of ICollection interface and exists since .NET Framework 2.0. Developers have always used this method before LINQ to check if List or another ICollection contains an item.

.Contains<T> is a part of LINQ. It is a query language which allows you to use this method with all IEnumerable collections, even arrays or custom; data sources likes databases; data formats like JSON or XML etc.

Actually, when you call LINQ .Contains<T> on IEnumerable collection which is ICollection (for example, List<T>), it does call its own ICollection.Contains method.

public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)
{
  ICollection<TSource> collection = source as ICollection<TSource>;
  if (collection != null)
    return collection.Contains(value);
  return Enumerable.Contains<TSource>(source, value, (IEqualityComparer<TSource>) null);
}

Upvotes: 0

Related Questions