# Sunday, April 22, 2007
« Comparing .NET 3.5 to 2.0 and 1.1 | Main | ISessionManager with NHibernate.Mapping.... »
Adding to my previous post, I thought I would also add an example that uses the new LINQ query expression syntax.  The example is pretty much the same as the last, except that I added one additional person to the list and added an aggregate.

public static void DotNet35WithQueryExpresion()
{
    IList<Person> people = new List<Person>()
    {
        new Person() { Age = 28, FirstName = "Shawn", LastName = "Neal" },
        new Person() { Age = 16, FirstName = "Isabella", LastName = "Neal" },
        new Person() { Age = 15, FirstName = "Joe", LastName = "Velope" },
        new Person() { Age = 43, FirstName = "John", LastName = "Smoe" }
    };

    IEnumerable<Person> teens = from p in people where p.Age < 20 && p.Age > 12 select p;
    Console.WriteLine("The following people are teenagers:");
    teens.WriteAll();

    int sumOfAges = teens.Sum(p => p.Age);
    Console.WriteLine("Sum of all ages: {0}", sumOfAges);
}

Looks like I just wrote some statically checked SQL straight into my c# doesn't it?  Seeing how Ayende has declared that queries are a business concern (and I agree) and we now have LINQ, we can finally place our queries where they belong, in our domain/service layer or even our presentation layer.  You could put your queries there before, but the legions of Microsoft followers would cry out, "This is not the MS way!"  It should be much easier to convince the Microsoft drones that still insist on putting business logic in the database, i.e. stored procedures, that queries in fact belong in the application under unit test.  Yes, queries should be unit tested just like the rest of your application!  Remember that queries are business logic.

I'm still not sure if there is a LINQ query expression that I can apply in this scenario that would replace the lambda expression in the Sum function.  Any idea?

Comments are closed.