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();
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.
In Java, we can use String. join(",", list) to join a List String with commas.
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
You could use a combination of string.Join and linq:
string.Join(" AND ", list1.Select((e1, idx) => $"{e1} {list2[idx]} {list3[idx]}"));
You could use one of overloads EquiZip()
in MoreLINQ:
var res = string.Join(" AND ", list1.EquiZip(list2, list3, (x, y, z) => x + y + z));
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]}"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With