简体   繁体   中英

How to convert a IEnumerable to Dictionary

I have dictionary like this

Dictionary<MyStructure, MyObject>

MyStructure means public struct ... MyObject means a specific entity ...

Then through events I pass my dictionary as an

IEnumerable<MyObject> col = this.GetCollection().Values;

Then when I manage my event I use my IEnumerable but I want to convert it to a former dictionary to access its properties but I'm not able to do it. I try this.

        Dictionary<MyStructure, MyObject> dict =
            args.MyObjectCollection.ToDictionary(x => x.Key, y => y.Value);

I'm using "using System.Linq;" and Key and Value are not recognize. When I write point after x or y. The helper shows me the properties of the object MyObject.

when you make your IEnumerable, you loose your MyStructure Keys ... If you know a way to create the appropriate structure from the MyObject instances, then you can solve this ...

MyObjectCollection.ToDictionary(x=>makeStructFromMyObject(x), x=>x);


//... with...

private MyStruct makeStructFromMyObject(MyObject obj)
{
   //to be implemented by you
}

if you are looking for an alternative ... pass the whole dictionary from the point where it still has the original data

If your collection is not a collection of KeyValuePairs or some other type with Key and Value properties, you cannot call them. A collection of all the values is simply a collection of that type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM