我如何在c#中转换一个列表到字符串?
当我在List对象上执行toString时,我得到:
System.Collections.Generic.List`1[System.String]
我如何在c#中转换一个列表到字符串?
当我在List对象上执行toString时,我得到:
System.Collections.Generic.List`1[System.String]
当前回答
你的问题的直接答案是字符串。像其他人提到的那样加入。
然而,如果你需要一些操作,你可以使用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();
其他回答
也许你正在尝试
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.
字符串。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()。
如果你想把一个列表中的项目变成一个大的长字符串,可以这样做:字符串。myList加入(" ")。一些旧版本的框架不允许你传递IEnumerable作为第二个参数,所以你可能需要通过调用. toarray()将列表转换为数组。
这很难说,但也许你想要的是:
var myString = String.Join(String.Empty, myList.ToArray());
这将隐式地对列表中的每个项调用ToString()方法并将它们连接起来。
你的问题的直接答案是字符串。像其他人提到的那样加入。
然而,如果你需要一些操作,你可以使用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();