Anonymous collection initializer for a dictionary
Asked Answered
V

2

10

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

?

Vitta answered 29/11, 2009 at 11:8 Comment(1)
possible duplicate of A dictionary where value is an anonymous type in C#Caucasia
S
16

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.

Stockmon answered 29/11, 2009 at 11:22 Comment(0)
D
1

Yes, but only with great workaround, and only within a method.

This is how you can do it:

    static Dictionary<TKey, TValue> NewDictionary<TKey, TValue>(TKey key, TValue value)
    {
        return new Dictionary<TKey, TValue>();
    }
    public void DictRun()
    {

        var myDict = NewDictionary(new { url="a"},
            new { Text = "dollar", Url ="urlA"});
        myDict.Add(new { url = "b" }, new { Text = "pound", Url = "urlB" });
        myDict.Add(new { url = "c" }, new { Text = "rm", Url = "urlc" });
        foreach (var k in myDict)
        {
            var url= k.Key.url;
            var txt= k.Value.Text;

            Console.WriteLine(url);
            Console.WriteLine(txt);    
        }

    }

You can refer to this SO question for more info.

Drawbar answered 29/11, 2009 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.