advanced web statistics

LINQ, Lambda, and Generics: ReturnAll and Filter

8/9/2007 11:42:21 PM

After I created my first LINQ Application in Orcas I started reading some blogs and articles beyond the "Hello World"-iness of most of the tutorials.  I mentioned that I was interested in learning more about 3.5 Generics and that it what I spent the better part of my evening doing.

In that last (first) LINQ application I created I have a LinqHelper class. It's a little impractical as it has an Accounts class within it.  Normally I would have a Helper class composed of a couple of Generic methods and Reflection to take care of all the dirty work.  Again, I was just testing the waters.

More Generic Way of Doing Business
int fooId = 3;
Expression
<Func<Foo, bool>> predicate = foo => foo.Id.Equals(fooId);
List<Foo> fooList = LinqHelper.Filter<Foo>(predicate); 

I have updated my LinqHelper class to reflect some of what I have read about today.

static List<T> ReturnAll<T>() where T : class
{
   using (SimpleSchedulerDB database = new SimpleSchedulerDB())
   {
      return database.GetTable<T>().ToList<T>();
   }
}

public static List<T> Filter<T>(Expression<Func<T, bool>> predicate)
where
T : class
{
   using (SimpleSchedulerDB database = new SimpleSchedulerDB())
   {
      
return database.GetTable<T>().Where<T>(predicate).ToList<T>();
   }
}

Using the code
Expression<Func<Foo, bool>> predicate = foo => foo.Id.Equals(fooId);
List<Foo> fooList = LinqHelper.Filter<Foo>(predicate);

repeaterFooInformation.DataSource = fooList;
repeaterFooInformation.DataBind(); 

The Filter<T> class accepts an Expression<T, bool> predicate as a parameter.  After I get my initial table I filter the IQueryable<T> sequence based on the predicate.  The result is a subset of the original sequence and in this case I am only concerned about Foo's with certain Id's.  That IEnumerable<T> is then converted to a List<T>. There is a lot going on in that method!

Check out Joseph Albahari's PredicateBuilder class. Good stuff! A very elegant solution for creating Expression<> trees.

LINQ, Lambda, and Generics... serious business!

LINQ, Orcas

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!