Home > c# > Sometimes simple program surprises me

Sometimes simple program surprises me

December 18, 2010 Leave a comment Go to comments

I was really surprised today by behavior of following simple program.

5+5=9? How come double happy string was de-duplicated?

static void Main()
    var original = new List<string>()   
        { "I", "wish", "you", "merry", "christmas"  };
    var additions = new List<string>()  
        { "merry", "christmas", "and", "happy", "happy", "new", "year" };
    var newAdditionsOnly = additions.Where(s => !original.Contains(s));
    PrintItems("original", original);                   
        // original has 5 items: I, wish, you, merry, christmas
    PrintItems("newAdditionsOnly", newAdditionsOnly);   
        // newAdditionsOnly has 5 items: and, happy, happy, new, year    
        // adding 5 items to original
    PrintItems("original", original);                   
        // original has 9 items: I, wish, you, merry, christmas, and, happy, new, year
static void PrintItems(string itemsName, IEnumerable<string> items)
    Console.WriteLine("{0} has {1} items: {2}", 
                      string.Join(", ", items));

After a while I realized what’s going on… can you see it immediately?

Categories: c# Tags: ,
  1. Hong
    December 18, 2010 at 13:57

    Very interesting!

    Is it because of defer execution of LINQ?

    I guess List.AddRange calls List.Add(), and each time it calls the lamda express to check whether added element exists or not. so first “happy” added, seconded not.

    btw, items needs to convert to array before it pass to String.Join()

    • December 18, 2010 at 15:52

      Exactly! Maybe I was too tired, but it wasn’t obvious to me immediately.

      (btw, there is String.Join overload which takes IEnumerable)

      • Hong
        December 18, 2010 at 22:38

        I am still using 3.5, String.Join overload is in 4.0

  1. No trackbacks yet.

Leave a Reply

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 /  Change )

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s