从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
当前回答
下面是我用在其他语言中使用过的方法:
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();
}
其他回答
您可以使用ToArray将IList转换为数组,然后运行字符串。在阵列上执行Join命令。
Dim strs As New List(Of String)
Dim arr As Array
arr = strs.ToArray
我能看到的最简单的方法是使用LINQ聚合方法:
string commaSeparatedList = input.Aggregate((a, x) => a + ", " + x)
你也可以使用下面的方法将它转换为一个数组,使用其他人列出的方法之一:
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()。
特定需求时,我们应该用',用ex:
string[] arr = { "jj", "laa", "123" };
List<string> myList = arr.ToList();
// 'jj', 'laa', '123'
Console.WriteLine(string.Join(", ",
myList.ConvertAll(m =>
string.Format("'{0}'", m)).ToArray()));