Archive
Archive for the ‘c#’ Category
Sometimes simple program surprises me
December 18, 2010
3 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
original.AddRange(newAdditionsOnly);
// 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}",
itemsName,
items.Count(),
string.Join(", ", items));
}
After a while I realized what’s going on… can you see it immediately?