简体   繁体   English

在 C# 中将列表转换为字符串

[英]Convert a list to a string in C#

How do I convert a list to a string in C#?如何在 C# 中将列表转换为字符串?

When I execute toString on a List object, I get:当我在 List 对象上执行toString时,我得到:

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

Maybe you are trying to do也许你正在尝试做

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

You can replace "," with what you want to split the elements in the list by.您可以将“,”替换为您想要拆分列表中元素的内容。

Edit : As mention in the comments you could also do编辑:正如评论中提到的,你也可以这样做

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

Reference:参考:

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

我将根据我的直觉,假设您想要连接对列表的每个元素调用ToString的结果。

var result = string.Join(",", list.ToArray());

You could use string.Join :你可以使用string.Join

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

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

The result would be:结果将是:

Red    
Blue    
Green

As an alternative to Environment.NewLine , you can replace it with a string based line-separator of your choosing.作为Environment.NewLine的替代方案,您可以将其替换为您选择的基于字符串的行分隔符。

If you want something slightly more complex than a simple join you can use LINQ eg如果你想要比简单连接稍微复杂的东西,你可以使用 LINQ 例如

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

Will take ["A", "B", "C"] and produce "(a)(b)(c)"将取 ["A", "B", "C"] 并产生 "(a)(b)(c)"

String.Join(" ", myList) or String.Join(" ", myList.ToArray()) . String.Join(" ", myList)String.Join(" ", myList.ToArray()) The first argument is the separator between the substrings.第一个参数是子字符串之间的分隔符。

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

Depending on your version of .NET you might need to use ToArray() on the list first..根据您的 .NET 版本,您可能需要先在列表中使用 ToArray()。

You have a List<string> - so if you want them concatenated, something like你有一个List<string> - 所以如果你想让它们连接起来,就像

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

would work (in .NET 4.0 at least).会工作(至少在 .NET 4.0 中)。 The first parameter is the delimiter.第一个参数是分隔符。 So you could also comma-delimit etc.所以你也可以用逗号分隔等。

You might also want to look at using StringBuilder to do running concatenations, rather than forming a list.您可能还想考虑使用 StringBuilder 来运行串联,而不是形成一个列表。

The .ToString() method for reference types usually resolves back to System.Object.ToString() unless you override it in a derived type (possibly using extension methods for the built-in types).引用类型的.ToString()方法通常解析回System.Object.ToString()除非您在派生类型中覆盖它(可能使用内置类型的扩展方法)。 The default behavior for this method is to output the name of the type on which it's called.此方法的默认行为是输出调用它的类型的名称。 So what you're seeing is expected behavior.所以你看到的是预期的行为。

You could try something like string.Join(", ", myList.ToArray());你可以尝试像string.Join(", ", myList.ToArray()); to achieve this.为了达成这个。 It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier.这是一个额外的步骤,但可以将它放在System.Collections.Generic.List<T>上的扩展方法中,以使其更容易一些。 Something like this:像这样的东西:

public static class GenericListExtensions
{
    public static string ToString<T>(this IList<T> list)
    {
        return string.Join(", ", list);
    }
}

(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.) (请注意,这是自由编写且未经测试的代码。我目前手头没有编译器。所以您需要稍微试验一下。)

It's hard to tell, but perhaps you're looking for something like:这很难说,但也许您正在寻找类似的东西:

var myString = String.Join(String.Empty, myList.ToArray());

This will implicitly call the ToString() method on each of the items in the list and concatenate them.这将隐式调用列表中每个项目的 ToString() 方法并将它们连接起来。

The direct answer to your question is String.Join as others have mentioned.您的问题的直接答案是其他人提到的String.Join

However, if you need some manipulations, you can use Aggregate :但是,如果您需要一些操作,您可以使用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();

If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList) .如果您希望将列表中的项目转换为一个大的长字符串,请执行以下操作: String.Join("", myList) Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().某些旧版本的框架不允许您将 IEnumerable 作为第二个参数传递,因此您可能需要通过调用 .ToArray() 将列表转换为数组。

This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.当我尝试从文本文件中检索数据并将其存储在数组中然后将其分配给字符串变量时,此方法对我有所帮助。

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

Hopefully may help Someone!!!!希望可以帮助某人!!!!

这似乎对我有用。

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

如果您的列表具有字段/属性并且您想使用特定值(例如名字),那么您可以这样做:

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

The output输出

000111,000222,000333

转换列表<string>列出<object>在 C#<div id="text_translate"><p> 我有一个看起来像这样的字符串列表:</p><pre> var rawData = new List<string>(){ "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321"};</pre><p> 我有以下结构:</p><pre> public class Data { public string instrument { get; set; } public string positions { get; set; } }</pre><p> 我的目标是有一个字符串数据列表,在';'上分开 char 并转换为对象列表。</p><pre> var processedData = new List<Data>(); // processedData[0] ( instrument = EUR/USD, positions = 123 ) // processedData[1] ( instrument = EUR/GBP, positions = 321) // processedData[2] ( instrument = BTC/USD, positions = 2321)</pre><p> 你知道我该怎么做吗?</p></div></object></string> - Convert List<string> to List<object> in C#

暂无
暂无

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

相关问题 将字符串转换为列表 - C# - Convert String to List - c# 在 C# 中转换列表<dynamic>列出<string> - In C# Convert List<dynamic> to List<string> C#转换列表 <string> 列出 <TimeSpan> - C# Convert List<string> to List<TimeSpan> 转换列表 <string> 列表 <int> 在C#中 - Convert List<string> to List<int> in C# 转换列表<string>列出<object>在 C#<div id="text_translate"><p> 我有一个看起来像这样的字符串列表:</p><pre> var rawData = new List<string>(){ "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321"};</pre><p> 我有以下结构:</p><pre> public class Data { public string instrument { get; set; } public string positions { get; set; } }</pre><p> 我的目标是有一个字符串数据列表,在';'上分开 char 并转换为对象列表。</p><pre> var processedData = new List<Data>(); // processedData[0] ( instrument = EUR/USD, positions = 123 ) // processedData[1] ( instrument = EUR/GBP, positions = 321) // processedData[2] ( instrument = BTC/USD, positions = 2321)</pre><p> 你知道我该怎么做吗?</p></div></object></string> - Convert List<string> to List<object> in C# 如何将数据表转换为列表 <String> 在C#中 - how convert DataTable to List<String> in C# 将字符串列表转换为相应的int C# - Convert string list to corresponding int c# 从列表转换为C#中的字符串 - Convert from list to string in C# 如何将DriveInfo []转换为列表 <string> C# - How to convert DriveInfo[] to List<string> C# 转换列表 <string> 到c#中的DataRow - Convert a List<string> to DataRow in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM