C# 逗号;";项目清单
给定一个字符串列表,将这些字符串连接到一个逗号分隔的列表(末尾没有逗号)的最佳方法是什么。(VB.NET或C#)(使用StringBuilder或StringConcat。) 如果您确实关心空字符串,请使用以下连接函数:C# 逗号;";项目清单,c#,.net,vb.net,string,C#,.net,Vb.net,String,给定一个字符串列表,将这些字符串连接到一个逗号分隔的列表(末尾没有逗号)的最佳方法是什么。(VB.NET或C#)(使用StringBuilder或StringConcat。) 如果您确实关心空字符串,请使用以下连接函数: Function Join(ByVal delimiter As String, ByVal items As IEnumerable(Of String), Optional ByVal IgnoreEmptyEntries As Boolean = True) As Str
Function Join(ByVal delimiter As String, ByVal items As IEnumerable(Of String), Optional ByVal IgnoreEmptyEntries As Boolean = True) As String
Dim delim As String = ""
Dim result As New Text.StringBuilder("")
For Each item As String In items
If Not IgnoreEmptyEntries OrElse Not String.IsNullOrEmpty(item) Then
result.Append(delim).Append(item)
delim = delimiter
End If
Next
Return result.ToString()
End Function
有几种方法可以做到这一点,但它们基本上是一个主题的变体 伪代码:
For Each Item In Collection:
Add Item To String
If Not Last Item, Add Comma
我更喜欢的另一种方式是:
For Each Item In Collection:
If Not First Item, Add Comma
Add Item To String
编辑:我喜欢第二种方式的原因是每一项都是独立的。使用第一种方法,如果您稍后修改了逻辑,以便后续项可能不会被添加,那么您可能会在字符串的末尾出现一个多余的逗号,除非您还使前一项中的测试更智能,这是愚蠢的。或者您可以:
Separator = ""
For Each Item In Collection
Add Separator + Item To String
Separator = ", "
通过在第一次迭代中将分隔符设置为空字符串,可以跳过第一个逗号。少一个if语句。这可能更具可读性,也可能不更具可读性,这取决于您习惯于这样做:
lstItems.ToConcatenatedString(s => s, ", ")
如果要忽略示例中的空字符串:
lstItems
.Where(s => s.Length > 0)
.ToConcatenatedString(s => s, ", ")
工具箱中最流行的自定义聚合函数。我每天都使用它:
public static class EnumerableExtensions
{
/// <summary>
/// Creates a string from the sequence by concatenating the result
/// of the specified string selector function for each element.
/// </summary>
public static string ToConcatenatedString<T>(
this IEnumerable<T> source,
Func<T, string> stringSelector)
{
return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty);
}
/// <summary>
/// Creates a string from the sequence by concatenating the result
/// of the specified string selector function for each element.
/// </summary>
/// <param name="separator">The string which separates each concatenated item.</param>
public static string ToConcatenatedString<T>(
this IEnumerable<T> source,
Func<T, string> stringSelector,
string separator)
{
var b = new StringBuilder();
bool needsSeparator = false; // don't use for first item
foreach (var item in source)
{
if (needsSeparator)
b.Append(separator);
b.Append(stringSelector(item));
needsSeparator = true;
}
return b.ToString();
}
}
公共静态类EnumerableExtensions
{
///
///通过连接结果从序列创建字符串
///为每个元素指定的字符串选择器函数的。
///
公共静态字符串到concatenatedString(
这是一个数不清的来源,
Func字符串选择器)
{
返回EnumerableExtensions.ToConcatenatedString(源、stringSelector、String.Empty);
}
///
///通过连接结果从序列创建字符串
///为每个元素指定的字符串选择器函数的。
///
///分隔每个连接项的字符串。
公共静态字符串到concatenatedString(
这是一个数不清的来源,
Func字符串选择器,
字符串分隔符)
{
var b=新的StringBuilder();
bool needsSeparator=false;//不用于第一项
foreach(源中的var项)
{
如果(需要分离)
b、 附加(分隔符);
b、 追加(字符串选择器(项目));
needsSeparator=true;
}
返回b.ToString();
}
}
从String.Join-answer开始,要忽略空字符串(如果您使用的是.NET 3.5),可以使用一点Linq。e、 g
Dim Result As String
Dim Items As New List(Of String)
Items.Add("Hello")
Items.Add("World")
Result = String.Join(",", Items.ToArray().Where(Function(i) Not String.IsNullOrEmpty(i))
MessageBox.Show(Result)
你相信在.NET框架中有一个类提供了这个功能吗
public static string ListToCsv<T>(List<T> list)
{
CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
list.ForEach(delegate(T item)
{
commaStr.Add(item.ToString());
});
return commaStr.ToString();
}
公共静态字符串ListToCsv(列表)
{
CommaDelimitedStringCollection commaStr=新的CommaDelimitedStringCollection();
列表.ForEach(委托人(T项)
{
commaStr.Add(item.ToString());
});
返回commaStr.ToString();
}
感谢所有回复
“正确”的答案似乎取决于构建逗号分隔列表的上下文。我没有一个整洁的项目列表可以使用(必须使用一些东西作为示例…),但我有一个数组,根据不同的条件,它的项目可以添加到逗号分隔的列表中,也可以不添加到逗号分隔的列表中
所以我选择了一个
strResult = ""
strSeparator = ""
for i as integer = 0 to arrItems.Length - 1
if arrItems(i) <> "test" and arrItems(i) <> "point" then
strResult = strResult & strSeparator & arrItem(i)
strSeparator = ", "
end if
next
像往常一样,有很多方法可以做到这一点。我不知道任何一种方法比另一种方法更值得赞扬或推广。有些在某些上下文中更有用,而另一些则满足不同上下文的要求
再次感谢大家的投入
顺便说一句,带有“off the top of my head”代码示例的原始帖子并没有过滤长度为零的项目,而是在添加逗号之前等待结果字符串的长度大于零。可能效率不高,但我还没有测试过。又一次,它从我的头顶上消失了
Dim strResult As String = ""
Dim separator = ","
Dim lstItems As New List(Of String)
lstItems.Add("Hello")
lstItems.Add("World")
For Each strItem As String In lstItems
strResult = String.Concat(strResult, separator)
Next
strResult = strResult.TrimEnd(separator.ToCharArray())
MessageBox.Show(strResult)
其思想是使用String.TrimEnd()函数
解决方案必须使用StringBuilder
或Concat
方法吗
如果没有,可以使用staticString.Join
方法。例如(在C中):
有关此方法的更多详细信息,请参阅。如果您不必使用StringBuilder
或Concat
方法,也可以使用:
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();
}
}
}
这需要参考System.Configuration我喜欢它。我甚至没想过用linq来做这个。。。林克不能做什么?
Dim strResult As String = ""
Dim separator = ","
Dim lstItems As New List(Of String)
lstItems.Add("Hello")
lstItems.Add("World")
For Each strItem As String In lstItems
strResult = String.Concat(strResult, separator)
Next
strResult = strResult.TrimEnd(separator.ToCharArray())
MessageBox.Show(strResult)
string result = String.Join(",", items.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();
}
}
}