我如何在c#中转换一个列表到字符串?
当我在List对象上执行toString时,我得到:
System.Collections.Generic.List`1[System.String]
我如何在c#中转换一个列表到字符串?
当我在List对象上执行toString时,我得到:
System.Collections.Generic.List`1[System.String]
当前回答
也许你正在尝试
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.
其他回答
引用类型的. tostring()方法通常解析回System.Object.ToString(),除非在派生类型中重写它(可能为内置类型使用扩展方法)。此方法的默认行为是输出调用它的类型的名称。所以你看到的是预期行为。
你可以试试绳子之类的东西。Join(", ", myList.ToArray());为了达到这个目的。这是一个额外的步骤,但它可以放在System.Collections.Generic的扩展方法中。List<T>让它更简单。就像这样:
public static class GenericListExtensions
{
public static string ToString<T>(this IList<T> list)
{
return string.Join(", ", list);
}
}
(请注意,这是未经测试的免费代码。目前我手头没有编译器。所以你会想要尝试一下。)
这很难说,但也许你想要的是:
var myString = String.Join(String.Empty, myList.ToArray());
这将隐式地对列表中的每个项调用ToString()方法并将它们连接起来。
string strs="111,222,333"
string.Join(",",strs.Split(',').ToList().Select(x=>x.PadLeft(6,'0')).ToArray());
输出
000111,000222,000333
当我试图从文本文件中检索数据并将其存储在数组中,然后将其分配给一个字符串变量时,这种方法帮助了我。
string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");
string marRes = string.Join(Environment.NewLine, lines.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.