Maximus Decimus
Maximus Decimus

Reputation: 5311

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.

Upvotes: 2

Views: 16473

Answers (2)

DarkSquirrel42
DarkSquirrel42

Reputation: 10287

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

Upvotes: 3

Magus
Magus

Reputation: 1312

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.

Upvotes: 1

Related Questions