RSS 2.0 | Atom 1.0 | CDF

Navigation

Search

Categories

On this page

Generic Lists....I Love Them

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Send mail to the author(s) E-mail Shary

Total Posts: 26
This Year: 2
This Month: 0
This Week: 0
Comments: 4

Sign In

 Thursday, February 15, 2007
2/15/2007 10:50 PM (  |  )

I became a fan of generic Lists in .NET 2.0 about 5 months back and have not stopped loving them since. The power of a strongly-typed list amazes me everyday and I have used them 69 different ways to accomplish various goals. Just today, I was reviewing some code that I wrote about 6 months back, and I just about smacked myself. Here was a perfect refactoring opportunity to leverage the power of List<>. The combination of a Generic List with Anonymous Delegates is a power-pack worthy of  a standing ovation. Here’s the before:

    1 public List<Job> RetrieveJobListForCurrentProjects()

    2         {

    3             List<IProject> currentProjects = RetrieveCurrentProjects();

    4             List<Job> jobList = RetrieveJobList();

    5             List<Job> filteredJobList = new List<Job>();

    6 

    7             foreach (Job job in jobList)

    8             {

    9                 bool found = false;

   10                 foreach (Project project in currentProjects)

   11                 {

   12                     if (project.JobNumber == job.JobNumber)

   13                     {

   14                         found = true;

   15                         break;

   16                     }

   17                 }

   18                 if (!found)

   19                     filteredJobList.Add(job);

   20             }

   21             return filteredJobList;

   22         }

Yes, I could have traversed the list backwards and removed items, but that still doesn’t come close to what follows, thanks to .NET 2.0!

    1         public List<Job> RetrieveJobListForCurrentProjects()

    2         {

    3             List<IProject> currentProjects = RetrieveCurrentProjects();

    4             List<Job> filteredJobList = RetrieveJobList();

    5 

    6             foreach (IProject project in currentProjects)

    7             {

    8                 filteredJobList.RemoveAll(delegate(Job job) { return job.JobNumber == project.JobNumber; });

    9             }

   10 

   11             return filteredJobList;

   12         }

Ahhh..isn’t that more soothing to the eye and the mind. The funny thing is that I can no longer bring myself to write the earlier version, yet I know some people who repeatedly disagree with me and suggest that the first version is simpler and easier to read.

You Decide!

 

Comments [1] | | #