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

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


当前回答

希望这是最简单的方法

 string Commaseplist;
 string[] itemList = { "Test1", "Test2", "Test3" };
 Commaseplist = string.join(",",itemList);
 Console.WriteLine(Commaseplist); //Outputs Test1,Test2,Test3

其他回答

有点难看,但很管用:

string divisionsCSV = String.Join(",", ((List<IDivisionView>)divisions).ConvertAll<string>(d => d.DivisionID.ToString("b")).ToArray());

在您给它转换器之后,从列表中给您一个CSV(在本例中d => d.DivisionID.ToString("b"))。

Hacky但工作-可以成为一个扩展方法也许?

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

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

编辑:这是另一个例子

供你参考,.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)

下面是我用在其他语言中使用过的方法:

private string ToStringList<T>(IEnumerable<T> list, string delimiter)
{
  var sb = new StringBuilder();
  string separator = String.Empty;
  foreach (T value in list)
  {
    sb.Append(separator).Append(value);
    separator = delimiter;
  }
  return sb.ToString();
}

我在寻找一个好的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;
    }