Wednesday, June 27, 2012

expressions in C#

What follows is a rewrite of this code using Johnny, Sid, Steve, and Paul as defined here.

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
using System.Linq;
namespace Whatever.Tests
{
   [TestClass]
   public class IQueryableTest
   {
      [TestMethod]
      public void DataTest()
      {
         Expression<Func<Contact, bool>> expression = c =>
               c.Email.EndsWith("example.com");
         string Ok = @"server=.\sqlexpress;database=OK;Integrated Security=true;";
         DataContext dataContext = new DataContext(Ok);
         Table<Contact> contacts = dataContext.GetTable<Contact>();
         
         IEnumerable<Contact> unfilteredIEnumerableFromIQueryable = contacts.OrderBy(c
               => c.Name);
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.Count(),4);
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(0).Name,
               "Johnny");
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(1).Name,
               "Paul");
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(2).Name, "Sid");
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(3).Name,
               "Steve");
         
         IEnumerable<Contact> filteredIEnumerableFromIQueryable =
               contacts.Where(expression).OrderBy(c => c.Name);
         Assert.AreEqual(filteredIEnumerableFromIQueryable.Count(), 3);
         Assert.AreEqual(filteredIEnumerableFromIQueryable.ElementAt(0).Name,
               "Johnny");
         Assert.AreEqual(filteredIEnumerableFromIQueryable.ElementAt(1).Name, "Paul");
         Assert.AreEqual(filteredIEnumerableFromIQueryable.ElementAt(2).Name, "Steve");
         
         IEnumerable<Contact> filteredIEnumerableFromIEnumerable =
               unfilteredIEnumerableFromIQueryable.Where(expression.Compile()).OrderBy(c
               => c.Name);
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.Count(), 3);
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.ElementAt(0).Name,
               "Johnny");
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.ElementAt(1).Name, "Paul");
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.ElementAt(2).Name,
               "Steve");
      }
   }
}

 
 

An Expression type is an expression tree wrapping a predicate (a Func returning a bool) and may be used as a predicate in an IQueryable where clause as shown above! An expression tree can become SQL where a predicate itself cannot. .Compile() will dumb an expression tree down to be just a predicate so that it may be used against an IEnumerable!

No comments:

Post a Comment