C# 将字符串列表转换为单个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19345988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a list of strings to a single string
提问by user2869820
List<string> MyList = (List<string>)Session["MyList"];
MyList
contains values like: 12
34
55
23
.
MyList
包含以下值:12
34
55
23
。
I tried using the code below, however the values disappear.
我尝试使用下面的代码,但是值消失了。
string Something = Convert.ToString(MyList);
I also need each value to be separated with a comma (",
").
我还需要用逗号 (" ,
")分隔每个值。
How can I convert List<string> Mylist
to string
?
我怎样才能转换List<string> Mylist
为string
?
采纳答案by ProgramFOX
string Something = string.Join(",", MyList);
回答by MUG4N
Try this code:
试试这个代码:
var list = new List<string> {"12", "13", "14"};
var result = string.Join(",", list);
Console.WriteLine(result);
The result is: "12,13,14"
结果是: "12,13,14"
回答by Misha Zaslavsky
You can make an extension method for this, so it will be also more readable:
您可以为此创建一个扩展方法,因此它也将更具可读性:
public static class GenericListExtensions
{
public static string ToString<T>(this IList<T> list)
{
return string.Join(",", list);
}
}
And then you can:
然后你可以:
string Something = MyList.ToString<string>();
回答by Sam
Or, if you're concerned about performance, you could use a loop,
或者,如果您担心性能,可以使用循环,
var myList = new List<string> { "11", "22", "33" };
var myString = "";
var sb = new System.Text.StringBuilder();
foreach (string s in myList)
{
sb.Append(s).Append(",");
}
myString = sb.Remove(sb.Length - 1, 1).ToString(); // Removes last ","
This Benchmarkshows that using the above loop is ~16% faster than String.Join()
(averaged over 3 runs).
该基准测试表明,使用上述循环比String.Join()
(平均运行 3 次)快约 16% 。
回答by Falgantil
Entirely alternatively you can use LINQ, and do as following:
或者,您可以使用 LINQ,并执行以下操作:
string finalString = collection.Aggregate("", (current, s) => current + (s + ","));
However, for pure readability, I suggest using either the loop version, or the string.Join mechanism.
但是,为了纯粹的可读性,我建议使用循环版本或 string.Join 机制。
回答by modle13
I had to add an extra bit over the accepted answer. Without it, Unity threw this error:
我不得不在接受的答案上多加一点。没有它,Unity 会抛出这个错误:
cannot convert `System.Collections.Generic.List<string>' expression to type `string[]'
The solution was to use .ToArray()
解决方案是使用.ToArray()
List<int> stringNums = new List<string>();
String.Join(",", stringNums.ToArray())