What's the easiest way to create a collection of key, value1, value2 ?
Important to me is that it is easy & short to retrieve either value1 or value2 given the pair (please show an example)
I know I can do this -
class MyObject
{
internal string NameA { get; set; }
internal string NameB { get; set; }
}
class Other
{
Dictionary<string, MyObject> MyObjectCollection { get; set; }
private void function()
{
MyObjectCollection = new Dictionary<string, MyObject>()
{ { "key", new MyObject { NameA = "something", NameB = "something else" } } };
var valueA = MyObjectCollection["key"].NameA; // = "something"
}
}
Is there a better way?
The solution which is easiest to implement (Dictionary<String, Tuple<String, String>>) is not the one which is easiest to support and develop (what is MyObjectCollection[key].Value2?). So I suggest using your own class:
class MyPair {
public string NameA { get; internal set; }
public string NameB { get; internal set; }
public MyPair(nameA, nameB) {
NameA = nameA;
NameB = nameB;
}
public override String ToString() {
return $"NameA = {NameA}; NameB = {NameB}";
}
}
class Other {
// you don't want "set" here
// = new ... <- C# 6.0 feature
public Dictionary<string, MyPair> Data { get; } = new Dictionary<string, MyPair>() {
{"key", new MyPair("something", "something else")},
};
...
Other myOther = new Other();
String test = myOther.Data["key"].NameA;
You can use a Tuple:
Dictionary<string,Tuple<string,string>> MyObjectCollection {get; set;}
private void function()
{
MyObjectCollection = new Dictionary<string, Tuple<string,string>>();
MyObjectCollection.Add("key1", Tuple.Create("test1", "test2"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With