我如何在c#中转换一个列表到字符串?

当我在List对象上执行toString时,我得到:

System.Collections.Generic.List`1[System.String]


当前回答

如果你的列表有字段/属性,你想使用一个特定的值(例如FirstName),那么你可以这样做:

string combindedString = string.Join( ",", myList.Select(t=>t.FirstName).ToArray() );

其他回答

你可以用绳子。加入:

List<string> list = new List<string>()
{
    "Red",
    "Blue",
    "Green"
};

string output = string.Join(Environment.NewLine, list.ToArray());    
Console.Write(output);

结果将是:

Red    
Blue    
Green

作为环境的替代方案。NewLine,您可以用您选择的基于字符串的行分隔符替换它。

你的问题的直接答案是字符串。像其他人提到的那样加入。

然而,如果你需要一些操作,你可以使用Aggregate:

List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();

这似乎对我有用。

var combindedString = new string(list.ToArray());

也许你正在尝试

string combinedString = string.Join( ",", myList.ToArray() );

您可以将“,”替换为您想要分割列表中的元素的值。

编辑:正如评论中提到的,你也可以这么做

string combinedString = string.Join( ",", myList);

参考:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.

你有一个List<string> -如果你想把它们连接起来,就像这样

string s = string.Join("", list);

可以工作(至少在。net 4.0中)。第一个参数是分隔符。你也可以用逗号分隔等等。

您可能还希望使用StringBuilder来运行连接,而不是形成一个列表。