Archive for March, 2008

Just some LINQ code

Scott Hanselman put up a post showing some nifty LINQ code. I’ve been dabbling with it a little here and there, trying to see what it gave me. I like the new way of declaring member variables:

int _age;

public int Age

{

   get { return _age; }

   set { _age = value; }

}

 

is fairly verbose, and it doesn’t add any real value for readability. So, I’m a huge fan of this:

public int Age { get; set; }

 

which is identical in the eyes of the compiler, but way better for doing a code review.

I also like the vanishing need to add properties and appropriate constructors. I like being able to write

new Person(){Age = 11, Gender=Gender.Male, Name=“Vince”}

without needing to write something like this:

public Person(int age, Gender gender, string name)

I also like the simpler lambdas and other expressions. So, tonight I finally put together all the different basic features and had this running:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Collections;

 

namespace LinqStuff

{

  enum Gender

  {

    Male,

    Female

  }

 

class Person

{

   public int Age { get; set; }

   public Gender Gender { get; set; }

   public string Name { get; set; }

 

   public override string ToString()

   {

       return string.Format(“{0}: {1}: {2}”, Name, Age, Gender.ToString());

   }

}

 

class Program

{

   static void Main(string[] args)

   {

      var people = new List<Person>(new Person[] {

          new Person(){Age = 11, Gender=Gender.Male, Name=“Vince”},

          new Person(){Age = 6, Gender=Gender.Female, Name=“Angeline”},

          new Person(){Age = 5, Gender=Gender.Male, Name=“Phillip”}

      });

      var boys = from a in people where a.Gender == Gender.Male orderby a.Name select a;

      people.Add(new Person() { Age = 37, Gender = Gender.Female, Name = “Jean” });

 

      ListEm<Person>(boys);

 

      people.Add(new Person() { Age = 35, Gender = Gender.Male, Name = “Scott” });

      ListEm<Person>(boys);

}

 

stati
c
void ListEm<T>(IEnumerable<T> vals)

{

      new List<T>(vals).ForEach(a => Console.Write(a.ToString() + “,”));

      Console.WriteLine();

}

}

}

 

The coolest thing here? My wife is learning C#. She took one look at the code and was able to instantly see that boys would automatically update as the people collection changed. The syntax passes the ‘is it instantly grokkable’ test for my sample audience of 1. I do like the fact that this syntax does focus more on what I want done instead of having to prescribe how to do it.

Leave a comment

Follow

Get every new post delivered to your Inbox.