How-to ensure multiple collections have the same item count using LINQ
Is there any great way to ensure m开发者_如何学Goultiple collections have the same item count 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 };
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.
If all your collections implement ICollection
interface, you can put them into single List<ICollection>
and then apply the Mark's 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;
精彩评论