Reputation:
I have a basic List that looks something like this:
List<string> gameNames = new List<string>()
{
"Zelda",
"Mario",
"Metroid",
"Splatoon",
"Xenoblade",
};
I have another List that looks something like this:
List<string> gameData = new List<string>()
{
", Nintendo, Nintendo, 2017",
"Mario, Nintendo, Nintendo, 2017",
", Nintendo, Nintendo, 2017",
", Nintendo, Nintendo, 2017",
"Xenoblade, Nintendo, Monolith, 2017",
};
I want to replace the first "," of the gameData List with the respective value in the same index of gameNames.
So, the first element should look like:
"Zelda, Nintendo, Nintendo, 2017"
Right now, I am using a Zip method that appends the data, but it doesn't check to see if the value is ',', it just appends no matter what.
Here is an example:
List<string> gameData= gameNames.Zip(gameData, (x, y) => x + "," + y).ToList();
Upvotes: 1
Views: 71
Reputation: 8726
I would suggest to add the leading comma logic to the lambda, and leave everything else intact:
var merged = gameNames.Zip(gameData, (x, y) => x + (y.StartsWith(", ") ? String.Empty : ", ") + y).ToList();
So it uses the leading comma where present, and inserts one where missing.
Second version after clarification in OP:
var merged = gameNames.Zip(gameData, (x, y) => (y.StartsWith(", ") ? x + y : y)).ToList();
This keeps the value of gameNames
whenever it does not start with a comma+space, else concatenates.
Upvotes: 3
Reputation: 115
You can try this:
for (int i = 0; i < gameData.Count(); i++)
{
gameData[i] = gameNames[i] + gameData[i].Substring(gameData[i].IndexOf(","));
}
gameData[i].IndexOf(",") above will find the position of first "," and Substring will extract content after first ",". Then append contents from gameNames list.
Upvotes: 1