Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple string list with separator

I have three string list, the purpose is combine these list to a single string with separator.

List<string> list1=new List<string>{"A","B","C"};
List<string> list2=new List<string>{"=","<", ">"};
List<string> list3=new List<string>{"1","2","3"};

The final output is like following:

A=1 AND B<2 AND C>3

Is there any easy way to generate the final string? I used for loop, but it seems to be ugly. I know C# string has Join method to combine an array with separator. How to combine multiple arrays with separator?

Below is my code:

StringBuilder str = new StringBuilder();
for(int i=0; i< list1.count; i++)
{
    str.AppendFormat("{0}{1}{2} AND ", list1[i], list2[i], list3[i]);
}
str.Length = str.Length -5;
string final = str.ToString();
like image 633
Kerwen Avatar asked Mar 29 '18 07:03

Kerwen


People also ask

How do I join multiple strings in a List?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you combine a List of strings in Java?

In Java, we can use String. join(",", list) to join a List String with commas.


4 Answers

Use Linq Zip() twice:

string result = string.Join(" AND ", list1.Zip(list2, (l1, l2) => l1 + l2).Zip(list3, (l2, l3) => l2 + l3));

https://dotnetfiddle.net/ZYlejS

like image 190
fubo Avatar answered Oct 14 '22 14:10

fubo


You could use a combination of string.Join and linq:

string.Join(" AND ", list1.Select((e1, idx) => $"{e1} {list2[idx]} {list3[idx]}"));
like image 37
richej Avatar answered Oct 14 '22 14:10

richej


You could use one of overloads EquiZip() in MoreLINQ:

var res = string.Join(" AND ", list1.EquiZip(list2, list3, (x, y, z) => x + y + z));
like image 35
HelloWorld Avatar answered Oct 14 '22 13:10

HelloWorld


You could also use a combination of string.Join along with Enumerable.Range like so:

string result = string.Join(" AND ", Enumerable.Range(0, Math.Min(list1.Count, 
                                    Math.Min(list2.Count, list3.Count)))
                      .Select(i => $"{list1[i]} {list2[i]} {list3[i]}"));

if the lists are guaranteed to have the same size then it can be reduced to:

string b = string.Join(" AND ", Enumerable.Range(0, list1.Count)
                 .Select(i => $"{list1[i]} {list2[i]} {list3[i]}"));
like image 38
Ousmane D. Avatar answered Oct 14 '22 15:10

Ousmane D.