How to get a consistent .Count / .Length property for C# generic collections? -


list<t> has .count property, t<> arrays .length instead. presume because arrays fixed-length whereas others aren't, difference in syntax can still frustrating.

if refactor array list, therefore gives "does not contain definition .length" errors, , seems waste of time having change when .count , .length same.

is there way deal ? possible extend list<t> add .length property that's alias .count instance, , vice-versa generic array ? , bad idea reason ?

you can use count method provided linq.

this optimised use count property provided icollection<t> interface possible (or non-generic icollection interface in .net 4). arrays, list<t> etc optimised.

var yourlist = new list<string> { "the", "quick", "brown", "fox" }; int count1 = yourlist.count();  // uses icollection<t>.count property  var yourarray = new[] { 1, 2, 4, 8, 16, 32, 64, 128 }; int count2 = yourarray.count();  // uses icollection<t>.count property  var yourenumerable = yourarray.where(x => x > 42); int count3 = yourenumerable.count();  // no optimisation, iterates sequence 

alternatively, if wanted consistent count property of kind without running risk of iterating entire sequence in non-optimised case create own extension methods. (i wouldn't go down route.)

int count4 = yourlist.getcount();  // uses icollection<t>.count property int count5 = yourarray.getcount();  // uses icollection<t>.count property int count6 = yourenumerable.getcount();  // compile-time error  // ...  public static class collectionextensions {     public static int getcount<t>(this icollection<t> source)     {         if (source == null) throw new argumentnullexception("source");         return source.count;     }      public static int getcount(this icollection source)     {         if (source == null) throw new argumentnullexception("source");         return source.count;     } } 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -