How to ensure that multiple collections have the same item counter using LINQ

Is there a great way to ensure that multiple collections have the same item counter using LINQ?

+6
c # linq
source share
3 answers

Try the following:

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 checking the length of each collection and tracking unique values. Having one reporting account is in order, but if there are two (or more) different calculations, then all collections do not have the same length, so the result will be false.


Update. If collections are of different types, you can use a non-generic interface, as shown in this answer .

 var collections = new List<ICollection> { a, b, c, d }; 
+2
source share

Check if

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

Beware that it lists the collection. If the collection is expensive to enumerate (e.g. LINQ2SQL) or changes state (updates some data and / or logging), there is no great way to use LINQ.

+2
source share

If all your collections implement the ICollection interface, you can put them in a single List<ICollection> , and then apply the Mark method.

 var a = new List<int>(); var b = new List<double>(); var c = new List<float>(); var d = new List<string>(); var collections = new List<ICollection> { a, b, c, d }; var sameLength = collections.Select(c => c.Count).Distinct().Count() == 1; 
+2
source share

All Articles