Ker*_*wen 14 c# arrays string list
我有三个字符串列表,目的是将这些列表与带分隔符的单个字符串组合在一起.
List<string> list1=new List<string>{"A","B","C"};
List<string> list2=new List<string>{"=","<", ">"};
List<string> list3=new List<string>{"1","2","3"};
Run Code Online (Sandbox Code Playgroud)
最终输出如下:
A=1 AND B<2 AND C>3
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来生成最终的字符串?我用过循环,但似乎很难看.我知道C#string有一个Join方法来组合数组和分隔符.如何将多个数组与分隔符组合?
以下是我的代码:
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();
Run Code Online (Sandbox Code Playgroud)
fub*_*ubo 22
使用Linq Zip()两次:
string result = string.Join(" AND ", list1.Zip(list2, (l1, l2) => l1 + l2).Zip(list3, (l2, l3) => l2 + l3));
Run Code Online (Sandbox Code Playgroud)
https://dotnetfiddle.net/ZYlejS
ric*_*hej 10
你可以使用string.Join和linq的组合:
string.Join(" AND ", list1.Select((e1, idx) => $"{e1} {list2[idx]} {list3[idx]}"));
Run Code Online (Sandbox Code Playgroud)