I am trying to create a dictionary where the key is a property of the value object. However, I would like to build a value object in the dictionary add method. Is there a way to do this without using an intermediate variable?
For example, I would like to do the following, but, of course, the key value is not available when necessary.
Dictionary<int,SomeComplexObject> dict = new Dicionary<int,SomeComplexObject>{
{someComplexObject.Key, new SomeComplexObject {Key = 1, Name = "FooBar"},
{someComplexObject.Key, new SomeComplexObject {Key = 2, Name = "FizzBang"}
};
Should I do it ugly:
Dictionary<int,SomeComplexObject> dict = new Dicionary<int,SomeComplexObject>();
SomeComplexObject value1 = new SomeComplexObject{Key=1,Name = "FooBar"};
dict.Add(value1.Key,value1);
SomeComplexObject value2 = new SomeComplexObject{Key=2,Name = "FizzBang"};
dict.Add(value.Key,value2);
I do not think this is the same question as
How to use the object identifier as a key for the dictionary <K, V>
because I don’t ask specifically about the dictionary key, but if there is a way to access the property of the objects when the object is not created until it appears in the list of method parameters.