C# 从 IList<string> 或 IEnumerable<string> 创建逗号分隔列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/799446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:39:38  来源:igfitidea点击:

Creating a comma separated list from IList<string> or IEnumerable<string>

c#string

提问by Daniel Fortunov

What is the cleanest way to create a comma-separated list of string values from an IList<string>or IEnumerable<string>?

IList<string>或 中创建以逗号分隔的字符串值列表的最简洁方法是什么IEnumerable<string>

String.Join(...)operates on a string[]so can be cumbersome to work with when types such as IList<string>or IEnumerable<string>cannot easily be converted into a string array.

String.Join(...)string[]当诸如IList<string>或 之类的类型IEnumerable<string>无法轻松转换为字符串数组时,对 a 进行操作可能会很麻烦。

采纳答案by Jon Skeet

.NET 4+

.NET 4+

IList<string> strings = new List<string>{"1","2","testing"};
string joined = string.Join(",", strings);

Detail & Pre .Net 4.0 Solutions

详细信息 & Pre .Net 4.0 解决方案

IEnumerable<string>can be converted into a string array veryeasily with LINQ (.NET 3.5):

IEnumerable<string>可以使用 LINQ (.NET 3.5)非常轻松地转换为字符串数组:

IEnumerable<string> strings = ...;
string[] array = strings.ToArray();

It's easy enough to write the equivalent helper method if you need to:

如果您需要,编写等效的辅助方法很容易:

public static T[] ToArray(IEnumerable<T> source)
{
    return new List<T>(source).ToArray();
}

Then call it like this:

然后像这样调用它:

IEnumerable<string> strings = ...;
string[] array = Helpers.ToArray(strings);

You can then call string.Join. Of course, you don't haveto use a helper method:

然后就可以调用了string.Join。当然,你不具备使用一个辅助方法:

// C# 3 and .NET 3.5 way:
string joined = string.Join(",", strings.ToArray());
// C# 2 and .NET 2.0 way:
string joined = string.Join(",", new List<string>(strings).ToArray());

The latter is a bit of a mouthful though :)

不过后者有点难吃:)

This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) this one.

这可能是最简单的方法,而且性能也非常好 - 还有其他关于性能究竟是什么样的问题,包括(但不限于)这个

As of .NET 4.0, there are more overloads available in string.Join, so you can actually just write:

从 .NET 4.0 开始, 中有更多可用的重载string.Join,因此您实际上可以编写:

string joined = string.Join(",", strings);

Much simpler :)

简单得多:)

回答by JoshJordan

You can use .ToArray()on Listsand IEnumerables, and then use String.Join()as you wanted.

您可以使用.ToArray()onListsIEnumerables,然后String.Join()根据需要使用。

回答by Vikram

you can convert the IList to an array using ToArray and then run a string.join command on the array.

您可以使用 ToArray 将 IList 转换为数组,然后在该数组上运行 string.join 命令。

Dim strs As New List(Of String)
Dim arr As Array
arr = strs.ToArray

回答by Daniel Fortunov

The easiest way I can see to do this is using the LINQ Aggregatemethod:

我能看到的最简单的方法是使用 LINQAggregate方法:

string commaSeparatedList = input.Aggregate((a, x) => a + ", " + x)

回答by Richard

They can be easily converted to an array using the Linq extensions in .NET 3.5.

它们可以使用 .NET 3.5 中的 Linq 扩展轻松转换为数组。

   var stringArray = stringList.ToArray();

回答by Keith

We have a utility function, something like this:

我们有一个效用函数,像这样:

public static string Join<T>( string delimiter, 
    IEnumerable<T> collection, Func<T, string> convert )
{
    return string.Join( delimiter, 
        collection.Select( convert ).ToArray() );
}

Which can be used for joining lots of collections easily:

可用于轻松加入大量集合:

int[] ids = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233};

string csv = StringUtility.Join(",", ids, i => i.ToString() );

Note that we have the collection param before the lambda because intellisense then picks up the collection type.

请注意,我们在 lambda 之前有集合参数,因为智能感知然后选择集合类型。

If you already have an enumeration of strings all you need to do is the ToArray:

如果你已经有一个字符串枚举,你需要做的就是 ToArray:

string csv = string.Join( ",", myStrings.ToArray() );

回答by Brad

You could also use something like the following after you have it converted to an array using one of the of methods listed by others:

在使用其他人列出的方法之一将其转换为数组后,您还可以使用类似以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Configuration;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
            string[] itemList = { "Test1", "Test2", "Test3" };
            commaStr.AddRange(itemList);
            Console.WriteLine(commaStr.ToString()); //Outputs Test1,Test2,Test3
            Console.ReadLine();
        }
    }
}

Edit:Hereis another example

编辑:是另一个例子

回答by Paul Houle

I wrote a few extension methods to do it in a way that's efficient:

我编写了一些扩展方法来以一种高效的方式完成它:

    public static string JoinWithDelimiter(this IEnumerable<String> that, string delim) {
        var sb = new StringBuilder();
        foreach (var s in that) {
            sb.AppendToList(s,delim);
        }

        return sb.ToString();
    }

This depends on

这取决于

    public static string AppendToList(this String s, string item, string delim) {
        if (s.Length == 0) {
            return item;
        }

        return s+delim+item;
    }

回答by David Clarke

Arriving a little late to this discussion but this is my contribution fwiw. I have an IList<Guid> OrderIdsto be converted to a CSV string but following is generic and works unmodified with other types:

这次讨论有点晚了,但这是我的贡献。我有一个IList<Guid> OrderIds要转换为 CSV 字符串的内容,但以下是通用的,无需修改其他类型:

string csv = OrderIds.Aggregate(new StringBuilder(),
             (sb, v) => sb.Append(v).Append(","),
             sb => {if (0 < sb.Length) sb.Length--; return sb.ToString();});

Short and sweet, uses StringBuilder for constructing new string, shrinks StringBuilder length by one to remove last comma and returns CSV string.

短小精悍,使用 StringBuilder 构造新字符串,将 StringBuilder 长度缩小 1 以删除最后一个逗号并返回 CSV 字符串。

I've updated this to use multiple Append()'s to add string + comma. From James' feedback I used Reflector to have a look at StringBuilder.AppendFormat(). Turns out AppendFormat()uses a StringBuilder to construct the format string which makes it less efficient in this context than just using multiple Appends()'s.

我已将其更新为使用多个Append()'s 来添加字符串 + 逗号。根据 James 的反馈,我使用 Reflector 来查看StringBuilder.AppendFormat(). 原来AppendFormat()使用 StringBuilder 来构造格式字符串,这使得它在此上下文中的效率低于仅使用 multiple Appends()

回答by Xavier Poinas

FYI, the .NET 4.0 version of string.Join()has some extra overloads, that work with IEnumerableinstead of just arrays, including one that can deal with any type T:

仅供参考,.NET 4.0 版本string.Join()有一些额外的重载,这些重载不仅适用于IEnumerable数组,还包括可以处理任何类型的数组T

public static string Join(string separator, IEnumerable<string> values)
public static string Join<T>(string separator, IEnumerable<T> values)