Is there any great way to ensure multiple collections have the same item count using LINQ ?
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.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With