从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
当前回答
我的答案就像上面的聚合解决方案,但应该更少的调用堆栈,因为没有显式的委托调用:
public static string ToCommaDelimitedString<T>(this IEnumerable<T> items)
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
sb.Append(item.ToString());
sb.Append(',');
}
if (sb.Length >= 1) sb.Length--;
return sb.ToString();
}
当然,可以将签名扩展为独立于分隔符的。我真的不是sb.Remove()调用的粉丝,我想重构它为一个直接的while循环在IEnumerable上,并使用MoveNext()来确定是否写一个逗号。如果我发现了这个解,我就会把它贴出来。
这是我最初想要的:
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> converter)
{
StringBuilder sb = new StringBuilder();
var en = source.GetEnumerator();
bool notdone = en.MoveNext();
while (notdone)
{
sb.Append(converter(en.Current));
notdone = en.MoveNext();
if (notdone) sb.Append(delimiter);
}
return sb.ToString();
}
不需要临时数组或列表存储,也不需要StringBuilder Remove()或Length—hack。
在我的框架库中,我对这个方法签名做了一些变化,包括分隔符和转换器参数的每一种组合,分别使用“,”和x.ToString()作为默认值。
其他回答
你也可以使用下面的方法将它转换为一个数组,使用其他人列出的方法之一:
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 studentNames = string.Join(", ", students.Select(x => x.name));
这是另一个扩展方法:
public static string Join(this IEnumerable<string> source, string separator)
{
return string.Join(separator, source);
}
我能看到的最简单的方法是使用LINQ聚合方法:
string commaSeparatedList = input.Aggregate((a, x) => a + ", " + x)
我的答案就像上面的聚合解决方案,但应该更少的调用堆栈,因为没有显式的委托调用:
public static string ToCommaDelimitedString<T>(this IEnumerable<T> items)
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
sb.Append(item.ToString());
sb.Append(',');
}
if (sb.Length >= 1) sb.Length--;
return sb.ToString();
}
当然,可以将签名扩展为独立于分隔符的。我真的不是sb.Remove()调用的粉丝,我想重构它为一个直接的while循环在IEnumerable上,并使用MoveNext()来确定是否写一个逗号。如果我发现了这个解,我就会把它贴出来。
这是我最初想要的:
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> converter)
{
StringBuilder sb = new StringBuilder();
var en = source.GetEnumerator();
bool notdone = en.MoveNext();
while (notdone)
{
sb.Append(converter(en.Current));
notdone = en.MoveNext();
if (notdone) sb.Append(delimiter);
}
return sb.ToString();
}
不需要临时数组或列表存储,也不需要StringBuilder Remove()或Length—hack。
在我的框架库中,我对这个方法签名做了一些变化,包括分隔符和转换器参数的每一种组合,分别使用“,”和x.ToString()作为默认值。