0

I'm wondering of there is a way to update my dictionary if the key exists, adding more elements to vale. Something like this is the idea:

var dic = new Dictionary<int, object>();
foreach(var item in Fields)
   if(dic.ContainsKey(item.Key)){
      // here will go the logic
   }

For example, I have a key 0 with an array of 4 values. Then, when I go to that code I want that if key 0 exist then my array will be overwrite to an array of the 4 elements and another 4 elements (8 in total) and go on. Is it possible?

EDIT: I finally made it this way:


var dic = new Dictionary<int, object>();
foreach(var item in Fields)
   if(dic.ContainsKey(item.Key))
   {
      var temp = new Array[4]{1, 2, 3, 4};
      var temp2 = dic[item.Key];
      var len = temp.Length + temp2.Count();
      var rs = new object[len];
      for(int i=0; i<len/2; i++)
          rs[i] = temp;
      for(int i = len/2; i<len;i++)
          rs[i] = temp2;
      dic[item.Key] = rs;
   }
Weenhallo
  • 324
  • 2
  • 8
  • 3
    What is the reason for using `object` as dictionary value? – Guru Stron Nov 18 '21 at 13:22
  • @GuruStron you know, it allows it, everything is an object :) – Trevor Nov 18 '21 at 13:22
  • 1
    @zaggler no way =) – Guru Stron Nov 18 '21 at 13:24
  • @GuruStron just because you *can* doesn't mean you should... – Trevor Nov 18 '21 at 13:25
  • @guru-stron It's not my project and I receive object, so I have to use it. – Weenhallo Nov 18 '21 at 13:45
  • @zaggler no. What I need it something like if I have a key 0 and Value[] 1,2,3,4, then add to Value[] 5, 6, 7, 8 so at the end I should have key 0 and Value[] 1, 2, 3, 4, 5, 6, 7, 8 – Weenhallo Nov 18 '21 at 13:47
  • @Weenhallo then you need to get the [value](https://stackoverflow.com/a/24255650/1797425) of that key and check for your condition (check if array contains 1,2,3 or 4), if it meets your condition then assign new value (new array that contains 1,2,3,4,5,6,7,8) to that key. What isn't clear in that link I sent you, can you explain please? Maybe I am misunderstanding your requirements. – Trevor Nov 18 '21 at 13:49
  • 1
    @zaggler probably I didn't explain myself, English it's not my first language. But I made it. Thank you! – Weenhallo Nov 18 '21 at 14:20
  • @Weenhallo You're welcome, glad to be of help. Do you mind updating your post to include this update and how you addressed this issue? Also worth mentioning, you may just close this question as you've figured it out. – Trevor Nov 18 '21 at 14:21

0 Answers0