Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - how to write a collection (Dictionary?) with one key and two values [duplicate]

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?

like image 446
Ory Zaidenvorm Avatar asked Dec 07 '25 09:12

Ory Zaidenvorm


2 Answers

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;
like image 102
Dmitry Bychenko Avatar answered Dec 09 '25 23:12

Dmitry Bychenko


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"));               
}
like image 43
Alexander Derck Avatar answered Dec 09 '25 23:12

Alexander Derck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!