…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;

       }

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Muuda )

Twitter picture

You are commenting using your Twitter account. Log Out / Muuda )

Facebook photo

You are commenting using your Facebook account. Log Out / Muuda )

Google+ photo

You are commenting using your Google+ account. Log Out / Muuda )

Connecting to %s

Create a free website or blog at WordPress.com.