Reputation: 8944
I was wondering if I can compare size of many lists in a elegant and fast way.
Basically this is my problem, I need to assert that 6 lists have the same size. So the usual way is something like (warning ugly code..):
if (list1.Count == list2.Count && list1.Count == list3.Count && .....) {
//ok, so here they have same size.
}
Some Jedi alternatives here?
Upvotes: 11
Views: 4156
Reputation: 52137
If you make this kind of comparison at just one place, then it is probably not worth trying to make it shorter (especially if it impacts the performance).
However, if you compare list lengths at more than one place, it is perhaps worthwhile putting it in a function then reusing it many times:
static bool SameLength<T>(params IList<T>[] lists) {
int len = -1;
foreach (var list in lists) {
int list_len = list.Count;
if (len >= 0 && len != list_len)
return false;
len = list_len;
}
return true;
}
static void Main(string[] args) {
// All of these lists have same length (2):
var list1 = new List<int> { 1, 2 };
var list2 = new List<int> { 3, 4 };
var list3 = new List<int> { 5, 6 };
var list4 = new List<int> { 7, 8 };
var list5 = new List<int> { 9, 10 };
var list6 = new List<int> { 11, 12 };
if (SameLength(list1, list2, list3, list4, list5, list6)) {
// Executed.
}
// But this one is different (length 3):
var list7 = new List<int> { 11, 22, 33 };
if (SameLength(list1, list2, list3, list7, list4, list5, list6)) {
// Not executed.
}
}
--- EDIT ---
Based on Dean Barnes' idea, you could even do this for extra-short implementation:
static bool SameLength<T>(params IList<T>[] lists) {
return lists.All(list => list.Count == lists[0].Count);
}
Upvotes: 2
Reputation: 2272
The all() method should do the trick: http://msdn.microsoft.com/en-us/library/bb548541.aspx.
Code should look like this, I think:
(new[] {list1, list2, list3, list4, list5, list6}).
All(list => list.Count == list1.Count);
Upvotes: 9
Reputation: 113442
How about with LINQ:
bool allSameSize = new[] { list1, list2, list3, list4, list5, list6 }
.Select(list => list.Count)
.Distinct()
.Take(2) // Optimization, not strictly necessary
.Count() == 1;
This idea works for any kind of sequence (not just lists), and will quick-reject as soon as two distinct counts are found.
On another note, is there any reason that the lists aren't part of a "list of lists" collection?
Upvotes: 3
Reputation: 393487
var lists = new [] { list1, list2, list3 ... };
bool diffLengths = lists.Select(list => list.Count).Distinct().Skip(1).Any();
Or
bool sameLen = new HashSet<int>(lists.Select(list => list.Count)).Count <= 1;
Upvotes: 1
Reputation: 96507
Using Enumerable.All
you can check that all lists match the same criteria:
var allLists = new[] { list1, list2, list3 };
bool result = allLists.All(l => l.Count == allLists[0].Count);
Or as a one-liner, but you would then need to refer to a particular list:
bool result = (new[] { list1, list2, list3 }).All(l => l.Count == list1.Count);
Upvotes: 7