从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?

string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。


当前回答

你可以在列表和IEnumerables上使用. toarray(),然后根据需要使用String.Join()。

其他回答

我在寻找一个好的c#方法来连接字符串时,就像使用MySql方法CONCAT_WS()一样,进行了这个讨论。此方法与string.Join()方法不同,它不会在字符串为NULL或空时添加分隔符。

CONCAT_WS (', ', tbl Lastname, tbl Firstname)。

如果名字为空,将只返回Lastname,同时

管柱。(", ", strLastname, strFirstname)

将返回strLastname + ", "在同样的情况下。

想要第一个行为,我写了以下方法:

    public static string JoinStringsIfNotNullOrEmpty(string strSeparator, string strA, string strB, string strC = "")
    {
        return JoinStringsIfNotNullOrEmpty(strSeparator, new[] {strA, strB, strC});
    }

    public static string JoinStringsIfNotNullOrEmpty(string strSeparator, string[] arrayStrings)
    {
        if (strSeparator == null)
            strSeparator = "";
        if (arrayStrings == null)
            return "";
        string strRetVal = arrayStrings.Where(str => !string.IsNullOrEmpty(str)).Aggregate("", (current, str) => current + (str + strSeparator));
        int trimEndStartIndex = strRetVal.Length - strSeparator.Length;
        if (trimEndStartIndex>0)
            strRetVal = strRetVal.Remove(trimEndStartIndex);
        return strRetVal;
    }

我们有一个效用函数,大概是这样的

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

它可以用来轻松地加入大量的集合:

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

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

注意,我们在lambda之前有一个集合参数,因为智能感知随后会拾取集合类型。

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

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

.NET 4 +。

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

Detail & Pre .Net 4.0解决方案

IEnumerable<string>可以很容易地用LINQ转换成一个字符串数组。NET 3.5):

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

如果你需要,编写等效的helper方法很容易:

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

然后这样称呼它:

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

然后你可以调用string.Join。当然,你不需要使用helper方法:

// 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());

后者有点拗口:)

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

从。net 4.0开始,字符串中有更多的重载可用。加入,你可以这样写

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

简单多了:)

我写了一些扩展方法,以一种有效的方式来做到这一点:

    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();
    }

这取决于

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

        return s+delim+item;
    }

你也可以使用下面的方法将它转换为一个数组,使用其他人列出的方法之一:

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();
        }
    }
}

编辑:这是另一个例子