Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to ensure multiple collections have the same item count using LINQ

Is there any great way to ensure multiple collections have the same item count using LINQ ?

like image 776
Yoann. B Avatar asked Mar 12 '11 19:03

Yoann. B


2 Answers

Check if

collection1.Count() == collection2.Count()

Beware that this enumerates the collection. If the collection is expensive to enumerate (like LINQ2SQL) or mutates the state (updates some data and/or logging) there is no great way at all using LINQ.

like image 22
Albin Sunnanbo Avatar answered Sep 28 '22 00:09

Albin Sunnanbo


Try this:

bool sameLength = (collections.Select(c => c.Count())
                              .Distinct()
                              .Take(2)   // Optional (for optimization).
                              .Count()) == 1;

or:

bool sameLength = !collections.Select(c => c.Count()).Distinct().Skip(1).Any();

It works by finding checking the length of each collection and keeping track of unique values. Having one distinct count is OK, but if there are two (or more) distinct counts then all the collections aren't the same length so the result is false.


Update: If the collections have different types you can use a non-generic interface as demonstrated in this answer.

var collections = new List<ICollection> { a, b, c, d };
like image 69
Mark Byers Avatar answered Sep 28 '22 01:09

Mark Byers