Learning Learning - 4 days ago 5
C# Question

Split and combine two different strings

I am trying to create a string and below is the thing which i am trying to achieve:

String first = "Previous.value1 | Previous.value2";
String second = "New.value1| New.value2";


I am trying to create final string like this:

string final ="generate Previous.value1 cross New.value1 ? Previous.value1 cross New.value2";


But problem is when i will have mismatch like below:

String first = "Previous.value1 | Previous.value2";
String second = "New.value1";


Then i want to have like this because i dont have matching value for Previous.Value2 in second variable:

string final ="generate Previous.value1 cross New.value1";


So far i am successfully in generating final string when i have same count of value in both the string.

string final = "generate";
if (first.Split('|').Count() - second.Split('|').Count() == 0)
{
int i = 0;
foreach (var item in first.Split('|').Count())
{
if (i == 0)
final = final + item + " cross " + second.Split('|')[i];
else
final = final + " ? " + item + " cross " + second.Split('|')[index];
i++;
}
}

Answer

Try this LINQ query (using the Zip extension method):

var zippedQry = first.Split('|').Zip(second.Split('|'),
    (f, s) => f.Trim() + " cross " + s.Trim());
string final = "generate " + String.Join(" ? ", zippedQry.ToArray());
Comments