我有一个数组。我的数组如下。
var Array = [["Dog","0","A","eat"],["cat","1","B","eat"]]
我想用其他值替换这个数组中某些索引中的值。比如应该是这样。
var newArray = [["Dog","big","house","eat"],["cat","small","forest","eat"]]
从例子中可以理解,“0 =大,1 =小”和“A=房子,B=森林”我如何使用for循环和C# Linq解决这个问题。
8e2ybdfx1#
不确定它是否有资格作为优雅,但你所描述的是一个翻译的问题,字典是非常好的。循环遍历每个数组中的每个字符串,如果翻译字典包含与该字符串相等的键,则进行替换。
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"]]
ovfsdjhp2#
这样和Linq一起做:
var testArray = array. Select(x => x. Select(y => y.Replace("0", "big").Replace("1","test")).ToArray()) .ToArray();
2条答案
按热度按时间8e2ybdfx1#
不确定它是否有资格作为优雅,但你所描述的是一个翻译的问题,字典是非常好的。
循环遍历每个数组中的每个字符串,如果翻译字典包含与该字符串相等的键,则进行替换。
ovfsdjhp2#
这样和Linq一起做: