…meie igapäevast IT’d anna meile igapäev…

2011-01-19

To LINQ or not to LINQ?

Filed under: Kogutud teotused,Programmeerimine — Sander @ 17:15:42
Tags: ,
private static List<long> FillDiscountList(HttpContextBase httpContextBase)

       {

           return (httpContextBase.Request.Form.Keys.Cast<string>().Where(key => key.StartsWith("discount_")).Select(

               key => new {key, id = key.Split('_')[1]}).Where(@t => httpContextBase.Request[@t.key] == "on").Select(

                   @t => long.Parse(@t.id))).ToList();

       }

Despite being a long-time LINQ fan, I think I will go with the original (below) and pass ReSharper’s helpful refactoring.

private static List<long> FillDiscountList(HttpContextBase httpContextBase)

       {

           var discounts = new List<long>();

           foreach (string key in httpContextBase.Request.Form.Keys)

           {

               if (key.StartsWith("discount_"))

               {

                   string id = key.Split('_')[1];

                   if (httpContextBase.Request[key] == "on")

                       discounts.Add(long.Parse(id));

               }

           }

           return discounts;

       }

Advertisements

3 kommentaari »

  1. Actually I think LINQ implementation can also be readable. Consider following example:

    private static List FillDiscountList(HttpContextBase httpContextBase)
    {
    return httpContextBase.Request.Form.Keys.Cast()
    .Where(key => key.StartsWith("discount_"))
    .Where(key => httpContextBase.Request[key] == "on")
    .Select(key => long.Parse(key.Split('_')[1]))
    .ToList();
    }

    Maybe if you declare id inside the if statement, ReSharper can properly figure out whats going on and produce better result. You don’t need that id variable in that point in the code anyway.

    Kommentaar kirjutas Sim — 2011-01-19 @ 23:25:58 | Vasta

    • It is not so much about readability as debugging. With one method chain, all you can see is whether the method was successful or not. But when it fails and you want to see why, you will need to start splitting the method chain.

      Kommentaar kirjutas Sander — 2011-01-20 @ 10:55:15 | Vasta

  2. Okey, that is one point. But on the other hand, you don’t need to debug every day whereas you are reading code almost always :)

    Kommentaar kirjutas Siim — 2011-01-20 @ 12:45:43 | Vasta


RSS feed for comments on this post. TrackBack URI

Lisa kommentaar

Täida nõutavad väljad või kliki ikoonile, et sisse logida:

WordPress.com Logo

Sa kommenteerid kasutades oma WordPress.com kontot. Logi välja / Muuda )

Twitter picture

Sa kommenteerid kasutades oma Twitter kontot. Logi välja / Muuda )

Facebook photo

Sa kommenteerid kasutades oma Facebook kontot. Logi välja / Muuda )

Google+ photo

Sa kommenteerid kasutades oma Google+ kontot. Logi välja / Muuda )

Connecting to %s

Create a free website or blog at WordPress.com.