Initializing Lookup

前端 未结 6 1629
轮回少年
轮回少年 2021-01-07 17:47

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          


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 18:08

    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 by calling ToLookup on an object that implements IEnumerable.

    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 { 
            { 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.

提交回复
热议问题