1

How to check two IEnumerables whether they have same count without running through them individually. Means I do not want to do this Count() == Count().

I would like to find a way to do that in one pass. Any ideas?

shankar.parshimoni
  • 1,289
  • 5
  • 22
  • 42
dev hedgehog
  • 8,698
  • 3
  • 28
  • 55

1 Answers1

3

This is not possible. Whatever approach you choose, you will have to run through both sequences.

The most straightforward way is to use the Count() method, where would be an O(1) if both sequences are List. In this case, the Count() fails to get the value of list's property called Count.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • Using `Count()` will take time proportional to the longer collection; better is to check whether either or both collections implement either `ICollection` or `ICollection`. If both do, compare their counts. If one does, read its count and try enumerating that N+1 items of the other. If the second collection ended after N, they match; if it ends sooner or doesn't end after N, they don't. If neither implements a counting interface, iterate them both *simultaneously*, and stop as soon as one reaches the end. – supercat Feb 19 '15 at 19:23