tags:

views:

85

answers:

4

Hi all how do i declare a new lookup class for a property in the object intialiser routine in c#?

eg

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

the category bit always get a compile error

thanks

+3  A: 

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

thedugas
+3  A: 

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.

jrotello
thanks jrotello x
Hannah
I tried this but get no intellisense, what is supposed to be in the ... portions?
Hannah
A: 

i have a property called Category that is of the type Lookup and i want to instantiate this property via new Component() { ID = 1, Name = "MOBO", Category = new Lookup}; but i cannot get past the compile errors. Thanks

Hannah
A: 

You can't just use ToLookup; you have to tell it how to find the keys and values:

// from ChaosPandion's code
using System.Linq; // make sure you have the using statement 

var component = new Component()  
{  
    ID = 1,  
    Name = "MOBO",  
    Category = (Lookup<int, string>)
       (new Dictionary<int, string>() { {1, "one"} })
       .ToLookup(p=>p.Key, p=>p.Value)
}  

I don't understand why you want to use a Lookup here instead of a dictionary, though.

Gabe