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

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


当前回答

在阅读本文之前,我刚刚解决了这个问题。我的解决方案如下:

   private static string GetSeparator<T>(IList<T> list, T item)
   {
       return (list.IndexOf(item) == list.Count - 1) ? "" : ", ";
   }

被称为:

List<thing> myThings;
string tidyString;

foreach (var thing in myThings)
{
     tidyString += string.format("Thing {0} is a {1}", thing.id, thing.name) + GetSeparator(myThings, thing);
}

我也可以这样简单地表达,也会更有效率:

string.Join(“,”, myThings.Select(t => string.format(“Thing {0} is a {1}”, t.id, t.name)); 

其他回答

.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);

简单多了:)

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

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

编辑:这是另一个例子

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

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

我认为创建逗号分隔的字符串值列表的最简单的方法是:

string.Join<string>(",", stringEnumerable);

下面是一个完整的例子:

IEnumerable<string> stringEnumerable= new List<string>();
stringList.Add("Comma");
stringList.Add("Separated");

string.Join<string>(",", stringEnumerable);

不需要创建helper函数,这是在。net 4.0及以上版本中内置的。

在这个讨论中有点晚了,但这是我的贡献。我有一个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();});

简短和甜蜜的,使用StringBuilder构造新字符串,缩小StringBuilder的长度以删除最后一个逗号,并返回CSV字符串。

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