Best way to change dictionary key

后端 未结 4 1353
忘掉有多难
忘掉有多难 2020-12-03 10:02

I am wondering is there a better way to change a dictionary key, for example:

var dic = new Dictionary();
dic.Add(\"a\", 1);
4条回答
  •  囚心锁ツ
    2020-12-03 10:34

    Do you like this simple code?

    var newDictionary= oldDictionary.ReplaceInKeys("_","-");
    
    
    

    It replace '_' with '-' in all keys


    If

    • type of your key is string

    and

    • you want replace a string with other string in all keys of the dictionary

    then use my way


    You just need to add the following class to your app:

    public static class DicExtensions{
    
        public static void ReplaceInKeys(this IDictionary oldDictionary, string replaceIt, string withIt)
        {
              // Do all the works with just one line of code:
              return oldDictionary
                     .Select(x=> new KeyValuePair(x.Key.Replace(replaceIt, withIt), x.Value))
                     .ToDictionary(x=> x.Key,x=> x.Value);
        }
    }
    

    I use Linq to change my dictionary keys (regenerate a dictionary by linq)

    The magic step is ToDictionary() method.


    Note: We can make an advanced Select include a block of codes for complicated cases instead of a simple lambda.

    Select(item =>{
                .....Write your Logic Codes Here....
    
                return resultKeyValuePair;
           })
    

    提交回复
    热议问题