Friday, February 19, 2010

Using IEnumerable

This method I posted a couple of days ago is my favorite way to get data from SQL server; it returns an IEnumerable of a private class.  Programming with IEnumerable requires a different thought process then when you are dealing with arrays.


For example when you are dealing with arrays you can check to see if they are empty by calling the Length property and comparing it against zero.  Which would be very expensive if you returning all the rows from SQL server call just to see if one row existed.  However, with IEnumerable you only need one row to “prove” that some exist.  Here is my IEnumerable HasMembers() method.


   1:  public Boolean HasMembers
   2:  {
   3:     get
   4:     {
   5:         foreach(Member member in Members())
   6:            return(true);
   8:         return(false);
   9:      }
  10:  }

Along with my Members() method that returns the IEnumerable, I include this method to quickly check for existence of members.



1 comment:

  1. How about:
    get { return Members().Any(); }