How to get a string array of all keys from a dictionary and change each string in the same way

An easy and simple (but not very good) way is to simply get an array of keys and repeat it updating each row.

string[] mapKeys = myDictionary.Keys.ToArray();

    for (int i = 0; i < mapKeys.Length; i++)
        mapKeys [i] = mapKeys [i].Replace("substringToRemove", "");

But is there a way to do this in 1 line of code (e.g. using LINQ)?

+4
source share
2 answers
mapKeys = mapKeys.Select(o=>o.Replace("substringToRemove", string.Empty)).ToArray();

or from your myDictionary:

string[] mapKeys = myDictionary.Keys.Select(o=>o.Replace("substringToRemove", string.Empty)).ToArray();
+5
source

You can use below LINQ:

mapKeys = mapKeys.Select( s => s.Replace("substringToRemove",string.Empty)).ToArray();
+3
source

Source: https://habr.com/ru/post/1648765/


All Articles