0

I am using the below code to check if two lists are equal.

var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;

The only thing I do not understand is how does ints2.Contains work. As far as I know, Contains() is a method and takes a parameter. As we can see here, Contains is not taking any parameter. Note - ints1 and ints2 are two different lists.

Bagdan Gilevich
  • 1,231
  • 1
  • 11
  • 17
Mainak Sikdar
  • 113
  • 1
  • 2
  • 9
  • Check [this](https://stackoverflow.com/questions/22173762/check-if-two-lists-are-equal/22173821) stackoverflow answer – Liquid Core Aug 28 '18 at 13:47
  • 3
    You should at least switch the order because the `Count` check is much cheaper – Tim Schmelter Aug 28 '18 at 13:49
  • 1
    By the way, your query doesn't take into account how often the ints are contained. So the first list could contain `1,2,1` and the second `1,2,2` and both are considered equal. It also ignores the order. If you want strict equal you can use [`Enumerable.SequenceEqual`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?view=netframework-4.7.2). – Tim Schmelter Aug 28 '18 at 13:56
  • What's important to note here is that *`All`* is a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function). If you're not familiar with that concept, I could easily see the source for confusion. And I don't think that that aspect is talked of in the linked dupe nor the single current answer here. – Damien_The_Unbeliever Aug 28 '18 at 13:57
  • Interesting that you would consider `ints1 = new List { 1, 1, 1 }` equal to `ints2 = new List { 1, 2, 3 }` :) – Rufus L Aug 28 '18 at 14:30
  • If the lists are sorted, you can use `SequenceEqual` to compare elements and count, otherwise you can use `GroupBy` as well to sort them on the fly for comparison: `var areEqual = ints1.OrderBy(i => i).SequenceEqual(ints2.OrderBy(i => i));` – Rufus L Aug 28 '18 at 14:36
  • @LiquidCore - I have followed the link you provided and I got the above expression in my question from the link itself but nowhere it explains my answer. – Mainak Sikdar Aug 29 '18 at 07:29

1 Answers1

5

That's called a method group. It's basically a shorcut for this:

ints1.All(x => ints2.Contains(x))
Selman Genç
  • 100,147
  • 13
  • 119
  • 184