2

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Maximus Decimus
  • 4,901
  • 22
  • 67
  • 95
  • 1
    You can't, you've only got the values, not the keys anymore. You'll need to fix your event so it passes IDictionary<> or `IEnumerable` instead. Also consider whether this is necessary at all, it won't be when you also expose the dictionary through a property or GetXxx() method on the sender. Events should normally only pass the data that's only valid at the specific moment in time that the event is raised and can't be reasonably obtained another way. Passing a dictionary is a code smell, too many odds that the event receiver stores a stale copy of the data. – Hans Passant Nov 04 '13 at 23:34

2 Answers2

3

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

DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
1

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.

Magus
  • 1,302
  • 9
  • 16