一匿名字典集合初始 [英] Anonymous collection initializer for a dictionary

查看:171
本文介绍了一匿名字典集合初始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能隐含申报下一词典<超链接,匿名>

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

推荐答案

怎么样:

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

不过,你可以只的foreach 列表/阵列上...

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

您只有在你通过(唯一的)关键需要O(1)查找需要一本字典。

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

这篇关于一匿名字典集合初始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆