3

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?

Ory Zaidenvorm
  • 896
  • 1
  • 6
  • 20

3 Answers3

4

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

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"));               
}
Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
  • Are there any benefits vs. using a custom class aside from the few lines of code saved? – Ory Zaidenvorm Mar 22 '16 at 08:38
  • 1
    @OryZaidenvorm Not really, I only use them internally because they're easier than defining a struct/class for everything. I wouldn't recommend exposing a Tuple as end result – Alexander Derck Mar 22 '16 at 08:41
0
List<MyObject> list = new List<MyObject>();
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));

The first lambda lets you pick the key, the second one picks the value.

Eminem
  • 7,206
  • 15
  • 53
  • 95