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

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


当前回答

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

你可以这样做:

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

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

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

其他回答

如果你想要连接的字符串在对象列表中,那么你也可以这样做:

var studentNames = string.Join(", ", students.Select(x => x.name));

您可以使用ToArray将IList转换为数组,然后运行字符串。在阵列上执行Join命令。

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

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

   var stringArray = stringList.ToArray();

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

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

编辑:这是另一个例子

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