从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
从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
其他回答
这是另一个扩展方法:
public static string Join(this IEnumerable<string> source, string separator)
{
return string.Join(separator, source);
}
在这个讨论中有点晚了,但这是我的贡献。我有一个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()效率更低。
你也可以使用下面的方法将它转换为一个数组,使用其他人列出的方法之一:
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;
}
我知道现在回答这个问题有点晚了,但它可能会对那些在这里寻找这个问题答案的人有所帮助。
你可以这样做:
var finalString = String.Join(",", ExampleArrayOfObjects.Where(newList => !String.IsNullOrEmpty(newList.TestParameter)).Select(newList => newList.TestParameter));
使用ExampleArrayOfObjects。我们将在哪里创建一个非空值的新对象列表
然后进一步在新的对象列表上使用. select,以","作为分隔符连接并生成最终字符串。