none
how to update value in dictionary but not via key? RRS feed

  • Question

  • String strA = "first", strB = "value1";
    
    MyDic.Add(strA, strB);
    
    console.write(MyDic[str1]);
    
    strB = "value2";
    
    console.write(MyDic[str1]);

    I would like the second output is "value2", but not update via key

    how to do it?

    Thanks

    Tuesday, November 13, 2018 8:37 AM

Answers

  • Maybe use another dictionary:

    public class MyText

    {

        public string Value;

     

        public override string ToString()

        {

            return Value;

        }

    }

     

    . . .

    Dictionary<string, MyText> MyDic = new Dictionary<string, MyText>();

     

    String strA = "first", strB = "value1";

     

    MyText t = new MyText { Value = strB };

     

    MyDic.Add( strA, t);

     

    Console.WriteLine( MyDic[strA] );

     

    t.Value = "value2";

     

    Console.WriteLine( MyDic[strA] );


    • Marked as answer by _Wayne56 Wednesday, November 14, 2018 1:06 AM
    Tuesday, November 13, 2018 11:27 AM

All replies

  • How should it be possible, to "update" a specific value in a dictionary without using the key?

    You can update it theoretically using a kind of plain array access, but then you cannot be sure that you have changed to correct directory entry. Cause the identity of a directory entry is defined by its key and only by its key.

    Tuesday, November 13, 2018 9:12 AM
  • Maybe use another dictionary:

    public class MyText

    {

        public string Value;

     

        public override string ToString()

        {

            return Value;

        }

    }

     

    . . .

    Dictionary<string, MyText> MyDic = new Dictionary<string, MyText>();

     

    String strA = "first", strB = "value1";

     

    MyText t = new MyText { Value = strB };

     

    MyDic.Add( strA, t);

     

    Console.WriteLine( MyDic[strA] );

     

    t.Value = "value2";

     

    Console.WriteLine( MyDic[strA] );


    • Marked as answer by _Wayne56 Wednesday, November 14, 2018 1:06 AM
    Tuesday, November 13, 2018 11:27 AM
  • Do you mean by looking for it in the dictionary if present without the key ? if yes, then you could do it like following:

    var valueFound = MyDic.FirstOrDefault(x => x.Value == "value2");

    and then you could do :

    var key = valueFound.Key;
    var Value = valueFound.Value;

    Hope it helps!


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, November 13, 2018 12:06 PM