Saturday, August 4, 2007

Playing Favorites

Can a man favor one piece of code over another? Will the neglected code lead a life of misery because it did not know it's father's love? No, unless you're on the verge of writing some AI that needs to be reviewed before you go any further...

Over the years, I have written lots of T-SQL and .NET code. I'm always on the lookout for development language enhancements that make it easier to accomplish the same tasks with fewer lines of code. Among my favorite enhancements are sorting and filtering with C# 2.0 Generics.

Let's start with a simple Employee object:

public class Employee
{
string _firstName, _lastName;
decimal _salary;
public Employee(string firstName, string lastName, decimal salary) { _firstName = firstName; _lastName = lastName; _salary = salary; }
public string FirstName
{
get { return _firstName; }
}
public string LastName
{
get { return _lastName; }
}
public decimal Salary
{
get { return _salary; }
}
}


Let's create a Generic list of Employees:

List<employee> employeeList = new List<employee>();
employeeList.Add(new Employee("John", "Walker", 35000M));
employeeList.Add(new Employee("April", "Aagard", 45000M));
employeeList.Add(new Employee("Joann", "Wilten", 50000M));


List<T>.ForEach returns all of the items in the list:

Console.WriteLine("List all employees");
employeeList.ForEach(delegate(Employee em) {
Console.WriteLine(
string.Format("Name: {0} {1}, Salary: {2}",
em.FirstName, em.LastName, em.Salary.ToString()));});
Console.WriteLine();


List<T>.FindAll filters the list:

Console.WriteLine("Filtered by salary (where salary > 40000)");
List<employee> wellCompensatedList = employeeList.FindAll(delegate(Employee em) { return em.Salary > 40000M; });
wellCompensatedList.ForEach(delegate(Employee em)
{
Console.WriteLine(
string.Format("Name: {0} {1}, Salary: {2}",
em.FirstName, em.LastName, em.Salary.ToString()));
});
Console.WriteLine();


List<T>.Sort reorders the list:

Console.WriteLine("Sorted by last name ascending");
employeeList.Sort(delegate(Employee em1, Employee em2) { return em1.LastName.CompareTo(em2.LastName); });
employeeList.ForEach(delegate(Employee em)
{
Console.WriteLine(
string.Format("Name: {0} {1}, Salary: {2}",
em.FirstName, em.LastName, em.Salary.ToString()));
});
Console.ReadLine();


As you can see, the Generic list methods FindAll, ForEach and Sort, when combined with anonymous methods, allow you to easily manipulate your lists. Clean and simple code. No wonder it's my favorite. What code is your favorite?

No comments: