Search code examples
c#dictionaryienumerableconverters

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.


Solution

  • 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