从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
当前回答
您可以使用ToArray将IList转换为数组,然后运行字符串。在阵列上执行Join命令。
Dim strs As New List(Of String)
Dim arr As Array
arr = strs.ToArray
其他回答
我写了一些扩展方法,以一种有效的方式来做到这一点:
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;
}
由于我在搜索对象列表的特定属性(而不是ToString())时到达这里,这里是对接受的答案的补充:
var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
.Select(i => i.FirstName));
在阅读本文之前,我刚刚解决了这个问题。我的解决方案如下:
private static string GetSeparator<T>(IList<T> list, T item)
{
return (list.IndexOf(item) == list.Count - 1) ? "" : ", ";
}
被称为:
List<thing> myThings;
string tidyString;
foreach (var thing in myThings)
{
tidyString += string.format("Thing {0} is a {1}", thing.id, thing.name) + GetSeparator(myThings, thing);
}
我也可以这样简单地表达,也会更有效率:
string.Join(“,”, myThings.Select(t => string.format(“Thing {0} is a {1}”, t.id, t.name));
我知道现在回答这个问题有点晚了,但它可能会对那些在这里寻找这个问题答案的人有所帮助。
你可以这样做:
var finalString = String.Join(",", ExampleArrayOfObjects.Where(newList => !String.IsNullOrEmpty(newList.TestParameter)).Select(newList => newList.TestParameter));
使用ExampleArrayOfObjects。我们将在哪里创建一个非空值的新对象列表
然后进一步在新的对象列表上使用. select,以","作为分隔符连接并生成最终字符串。
我认为创建逗号分隔的字符串值列表的最简单的方法是:
string.Join<string>(",", stringEnumerable);
下面是一个完整的例子:
IEnumerable<string> stringEnumerable= new List<string>();
stringList.Add("Comma");
stringList.Add("Separated");
string.Join<string>(",", stringEnumerable);
不需要创建helper函数,这是在。net 4.0及以上版本中内置的。