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

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


当前回答

使用. net 3.5中的Linq扩展,可以很容易地将它们转换为数组。

   var stringArray = stringList.ToArray();

其他回答

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

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

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

编辑:这是另一个例子

我知道现在回答这个问题有点晚了,但它可能会对那些在这里寻找这个问题答案的人有所帮助。

你可以这样做:

var finalString = String.Join(",", ExampleArrayOfObjects.Where(newList => !String.IsNullOrEmpty(newList.TestParameter)).Select(newList => newList.TestParameter));

使用ExampleArrayOfObjects。我们将在哪里创建一个非空值的新对象列表

然后进一步在新的对象列表上使用. select,以","作为分隔符连接并生成最终字符串。

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

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

由于我在搜索对象列表的特定属性(而不是ToString())时到达这里,这里是对接受的答案的补充:

var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
                                 .Select(i => i.FirstName));