-3

what is the difference between using exists over contains

var s = new int[] { 1, 2, 3, 4, 5 };
dbset.where(x => s.contains(x.id);

or

var s = new int[] { 1, 2, 3, 4, 5 };
dbset.Where(x => s.Exists(y => x.id));
gh9
  • 10,169
  • 10
  • 63
  • 96

1 Answers1

3
  1. Exists is a method of List<T>, there is no such method on array or IEnumerable<T> 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.
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • +1, you did much better in explaining the difference between these two methods, than I. But could you also describe the difference between passing a raw value and a predicate? I just think this is crucial in understanding the key difference between these two methods (Because EF supports `Any` instead of `Exists`, so it's not like a big problem\difference here) – Ilya Ivanov Mar 18 '13 at 16:24
  • @IlyaIvanov sorry, didn't get you here :) Predicate is a part of Exists method signature, difference between passing raw value and predicate is simple - you either call this method with predicate, or your code do not compile – Sergey Berezovskiy Mar 18 '13 at 16:29
  • Well, for example, you can capture local variable in a predicate and access it in a predicate, thus creating more flexible conditions for comparison. ANYWAY - lets leave it for self study. Speaking about syntax - you answer is perfectly valid :) – Ilya Ivanov Mar 18 '13 at 16:31