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

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

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


当前回答

string strs="111,222,333"
string.Join(",",strs.Split(',').ToList().Select(x=>x.PadLeft(6,'0')).ToArray());

输出

000111,000222,000333

其他回答

如果你想要一些比简单的连接稍微复杂一点的东西,你可以使用LINQ。

var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");

将采用["A", "B", "C"]并产生"(A)(B)(C)"

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

然而,如果你需要一些操作,你可以使用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();

字符串。Join(" ", myList)或String。Join(" ", myList.ToArray())。第一个参数是子字符串之间的分隔符。

var myList = new List<String> { "foo","bar","baz"};
Console.WriteLine(String.Join("-", myList)); // prints "foo-bar-baz"

根据你的.NET版本,你可能需要先在列表中使用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,您可以用您选择的基于字符串的行分隔符替换它。

当我试图从文本文件中检索数据并将其存储在数组中,然后将其分配给一个字符串变量时,这种方法帮助了我。

string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");  
string marRes = string.Join(Environment.NewLine, lines.ToArray());

希望可以帮助某人!!!!