Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare size (Count) of many lists

Tags:

c#

list

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?

like image 451
Custodio Avatar asked Nov 11 '11 13:11

Custodio


2 Answers

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);
like image 92
Dean Barnes Avatar answered Oct 20 '22 11:10

Dean Barnes


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);
like image 24
Ahmad Mageed Avatar answered Oct 20 '22 12:10

Ahmad Mageed