Anonymous collection initializer for a dictionary

abatishchev picture abatishchev · Nov 29, 2009 · Viewed 12.1k times · Source

Is it possible to implicitly declare next Dictionary<HyperLink, Anonymous>:

{ urlA, new { Text = "TextA", Url = "UrlA" } },
{ urlB, new { Text = "TextB", Url = "UrlB" } }

so I could use it this way:

foreach (var k in dic)
{
   k.Key.Text = k.Value.Text;
   k.Key.NavigateUrl = k.Value.Url;
}

?

Answer

Marc Gravell picture Marc Gravell · Nov 29, 2009

How about:

var dict = new[] {
            new { Text = "TextA", Url = "UrlA" },
            new { Text = "TextB", Url = "UrlB" }
        }.ToDictionary(x => x.Url);
// or to add separately:
dict.Add("UrlC", new { Text = "TextC", Url = "UrlC" });

However, you could just foreach on a list/array...

var arr = new[] {
    new { Text = "TextA", Url = "UrlA" },
    new { Text = "TextB", Url = "UrlB" }
};
foreach (var item in arr) {
    Console.WriteLine("{0}: {1}", item.Text, item.Url);
}

You only need a dictionary if you need O(1) lookup via the (unique) key.