简体   繁体   中英

Replace Values from another array if contains same keys

I have the following collection

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

Then I have a lookup table, which contains keys that needs to be replaced:

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

The final result should be the original list with the values replaced from the lookup table

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

I was trying with the aggregate function in the following way:

    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));
for (var i = 0; i < collection.Length; i++)
{
    foreach (var k in keys)
    {
        collection[i] = collection[i].Replace(k.Item1, k.Item2);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM