简体   繁体   中英

Remove last character from dictionary<string, dictionary<string, string>> using C#

I have

Dictionary<string, Dictionary<string, string>>

My inner dictionary has the following data

{
  "1": {
    "message-Code1": "   0",
    "msg-Number-Pos11": "0",
    "msg-Number-Pos21": "0",
    "msg-Number-Pos31": " "
  },
  "2": {
    "message-Code2": "   0",
    "msg-Number-Pos12": "0",
    "msg-Number-Pos22": "0",
    "msg-Number-Pos32": " "
  }

But I want a out like below

{
  "1": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  },
  "2": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  }

Last character of the all the Key 's is removed ie 1 in the first set and 2 in the second set of result.

I was trying with below code

var result = dictionary.Where(pair => pair.Value.Remove(pair.Value.Key.Last()));

This is throwing an error. Can anyone help me in bringing the output that I need.

Basically you should create new "inner" dictionaries. That's easy to do though:

var replacedOuter = outerDictionary.ToDictionary(
   outerKey => outerKey, // Outer key stays the same
   outerValue => outerValue.ToDictionary(
       innerKey => innerKey.Substring(0, innerKey.Length - 1),
       innerValue => innerValue));

Note that if this creates any duplicate keys (ie if there were any keys that only differed by final character) an exception will be thrown by the inner ToDictionary call.

Since you cant change a dictionary key you would have to re-create the nested dictionary using your new key.

foreach (var item in dic.ToArray())
    dic[item.Key] = item.Value.ToDictionary(x => 
                      x.Key.Remove(x.Key.Length - 1), x => x.Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM