I am wondering is there a better way to change a dictionary key, for example:
var dic = new Dictionary();
dic.Add(\"a\", 1);
Do you like this simple code?
var newDictionary= oldDictionary.ReplaceInKeys
It replace
'_'with'-'in all keys
If
key is string and
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;
})