初始化Lookup< int,string> [英] Initializing Lookup<int, string>

查看:65
本文介绍了初始化Lookup< int,string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#的对象初始化程序例程中为属性声明新的查找类?

How do i declare a new lookup class for a property in the object initializer routine in c#?

例如

new Component() { ID = 1, Name = "MOBO", Category = new Lookup<int, string> } 

类别位始终会出现编译错误.

The category bit always get a compile error.

我有一个名为Category的属性,该属性的类型为Lookup<int, string>,我想通过

I have a property called Category that is of the type Lookup<int, string> and I want to instantiate this property via

new Component() { ID = 1, Name = "MOBO", Category = new Lookup<int, string> };

但是我无法克服编译错误.

But I cannot get past the compile errors.

推荐答案

每个MSDN文档中,Lookup类没有公共构造函数:

Per MSDN documentation, there is no public constructor for the Lookup class: http://msdn.microsoft.com/en-us/library/bb460184.aspx

您可以通过在实现IEnumerable<T>的对象上调用ToLookup来创建Lookup<TKey, TElement>的实例.

You can create an instance of a Lookup<TKey, TElement> by calling ToLookup on an object that implements IEnumerable<T>.

您将要执行以下操作:

new Component { ID = 1, Name = "MOBO", Category = new[] { … }.ToLookup(…) }

更新为地址注释:

我不确定您从何处获取类别信息,所以我会做些补充……

I'm not sure where you are getting your category info from, so I will make something up…

new Component {
    ID = 1, 
    Name = "MOBO", 
    Category = new Dictionary<int, string> { 
        { 3, "Beverages" }
        { 5, "Produce" }
    }.ToLookup(o => o.Key, o => o.Value)
}

我的猜测是您的类别将来自其他来源,而不是像我在此处那样实例化字典.

My guess is that your categories will come from some other source instead of instantiating a dictionary like I did here.

这篇关于初始化Lookup&lt; int,string&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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