Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

c# - Initializing Lookup<int, string>

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

E.g.

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

The category bit always get a compile error.


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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

You will want to do something like:

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

Update to address comments:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...