Home > Software design >  replace an element in a specific array with another value in C#
replace an element in a specific array with another value in C#

Time:12-01

There is one array for me. my array is as follows.

var Array = [["Dog","0","A","eat"],["cat","1","B","eat"]]

I want to replace the value in some indexes in this array with other values.

for example, it should be like this.

var newArray = [["Dog","big","house","eat"],["cat","small","forest","eat"]]

can be understood from the example, "0 = big, 1 = small" and "A=house, B=forest"

how can I solve this both with the for loop and using C# Linq.

CodePudding user response:

Unsure if it qualifies as elegant but what you're describing is a matter of translation, a Dictionary is very good for this.

Loop through each string in each array and replace if the translation dictionary contains a key equal to the string.

var Array = new string[][] {
    new string[] {"Dog", "0", "A", "eat" },
    new string[] {"Cat", "1", "B", "eat" }
};
//Array: [["Dog","0","A","eat"],["Cat","1","B","eat"]]

var TranslationDict = new Dictionary<string, string>() {
    { "0", "big" },
    { "1", "small" },
    { "A", "house" },
    { "B", "forest" },
};

for (int y = 0; y < Array.Length; y  ) {
    for (int x = 0; x < Array[y].Length; x  ) {
        if(TranslationDict.ContainsKey(Array[y][x])) {
            Array[y][x] = TranslationDict[Array[y][x]];
        }
    }
}

//Array: [["Dog","big","house","eat"],["Cat","small","forest","eat"]]

CodePudding user response:

Do it with linq like that:

var testArray = array.
Select(x => x.
Select(y => y.Replace("0", "big").Replace("1","test")).ToArray())
.ToArray();
  • Related