advanced web statistics

Chaining of Generic List Methods

12/19/2007 8:52:34 PM

I swear this will never get old.  It's not high-tech, but useful.  If you wanted to you could turn this into a 3-line method. I broke out into 2 lines for readability.

private static decimal RetrieveTotalByCode(string code, List<Foo> list)
{
   decimal total = 0m;

   list.FindAll(delegate (Foo predicate)
                     {
                        return predicate.Code.Equals(code);
                     }).ForEach(delegate (Foo foo)
                                 {
                                    total += foo.Property;
                                 });

   return total;
}

I've run into code in the past where there would literally be one method that would sum a property based on a fixed "code".  A perfect example would be sales by region.  You would have a Field in your database (property of an object) that is something like "RegionSold".  What if you had 77 regions? 77 methods?  I know people who would agree.

Here all you have to do is instantiate a List<T> of your Regions and for each region call this method and display to end-user however it is you are displaying to them.

So to person I used to work with, this one's for you.

C#, Code

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!