0

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.

2
  • 1
    Try it. If you have problems then show where your at. Then we help. Commented Dec 1, 2022 at 9:33
  • I actually tried to go into it with the for loop and equalize the if conditions. but I would like to see more elegant and readable codes. Commented Dec 1, 2022 at 9:38

2 Answers 2

2

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"]]
Sign up to request clarification or add additional context in comments.

1 Comment

I like the use of the dictionary. You could alternatively use .TryGetValue() in the if, so that you don't need to do the lookup twice.
1

Do it with linq like that:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.