从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
从IList<string>或IEnumerable<string>创建逗号分隔的字符串值列表的最干净的方法是什么?
string . join(…)操作在字符串[]上,因此当IList<string>或IEnumerable<string>等类型不能轻松转换为字符串数组时,处理起来很麻烦。
当前回答
这是另一个扩展方法:
public static string Join(this IEnumerable<string> source, string separator)
{
return string.Join(separator, source);
}
其他回答
由于我在搜索对象列表的特定属性(而不是ToString())时到达这里,这里是对接受的答案的补充:
var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
.Select(i => i.FirstName));
希望这是最简单的方法
string Commaseplist;
string[] itemList = { "Test1", "Test2", "Test3" };
Commaseplist = string.join(",",itemList);
Console.WriteLine(Commaseplist); //Outputs Test1,Test2,Test3
如果你想要连接的字符串在对象列表中,那么你也可以这样做:
var studentNames = string.Join(", ", students.Select(x => x.name));
我知道现在回答这个问题有点晚了,但它可能会对那些在这里寻找这个问题答案的人有所帮助。
你可以这样做:
var finalString = String.Join(",", ExampleArrayOfObjects.Where(newList => !String.IsNullOrEmpty(newList.TestParameter)).Select(newList => newList.TestParameter));
使用ExampleArrayOfObjects。我们将在哪里创建一个非空值的新对象列表
然后进一步在新的对象列表上使用. select,以","作为分隔符连接并生成最终字符串。
你也可以使用下面的方法将它转换为一个数组,使用其他人列出的方法之一:
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();
}
}
}
编辑:这是另一个例子