Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
Hannah Avatar asked Mar 02 '10 22:03

Hannah


2 Answers

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.

like image 52
jrotello Avatar answered Dec 10 '22 07:12

jrotello


From MSDN:

There is no public constructor to create a new instance of a Lookup<TKey, TElement>.
Additionally, Lookup<TKey, TElement> objects are immutable, that is, you cannot add or remove elements or keys from a Lookup<TKey, TElement> object after it has been created.

like image 23
dugas Avatar answered Dec 10 '22 06:12

dugas