简体   繁体   English

将字符串列表转换为单个字符串

[英]Convert a list of strings to a single string

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

string Something = string.Join(",", MyList);

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"

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 Benchmark shows that using the above loop is ~16% faster than String.Join() (averaged over 3 runs). 该Benchmark显示使用上述循环比String.Join()快了约16%(平均超过3次运行)。

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机制。

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>();

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM