如果包含相同的键,则从另一个数组替换值

时间:2014-03-06 17:03:18

标签: c# arrays

我有以下收藏

var collection = new []
{ 
   "First1",
   "Second2",
   "Third12"
}

然后我有一个查找表,其中包含需要替换的键:

var keys = new []
{ 
   Tuple.Create(1, "ABC"),
   Tuple.Create(2, "DEF")
}

最终结果应该是原始列表,其中的值已从查找表

中替换
var collection = new []
{ 
   "FirstABC",
   "SecondDEF",
   "ThirdABCDEF"
}

我正在尝试以下列方式使用聚合函数:

    string[] collection = new[]{"First#", "Second@"};

    Console.WriteLine("Before {0}", String.Join(" - ", collection));

    var keys = new[]{Tuple.Create("#", "ABC"),Tuple.Create("@", "CDE")};
    foreach ( var item in collection)
    {
        if() // my item is in any occurrence of the keys array
    }

    Console.WriteLine("After {0}", String.Join(" - ", collection));

1 个答案:

答案 0 :(得分:2)

for (var i = 0; i < collection.Length; i++)
{
    foreach (var k in keys)
    {
        collection[i] = collection[i].Replace(k.Item1, k.Item2);
    }
}