c#join string逗号分隔,但双引号内的所有值

时间:2017-05-03 16:56:46

标签: c#

我有一个字符串列表

new List<string> { "One", "Two", "Three", "Four", "Five", "Six" }

我想要一个包含完整内容的字符串(包括双引号)

"One", "Two", "Three", "Four", "Five", "Six"

因为会写一个文本文件,它将是一个数组[] = {my_string}

我尝试了这个没有成功

var joinedNames = fields.Aggregate((a, b) => "\"" + a + ", " + b + "\"");

小LINQ帮助将非常感激:)

5 个答案:

答案 0 :(得分:16)

var joinedNames = "\"" + string.Join("\", \"", fields) + "\"";

答案 1 :(得分:9)

您可以使用Linq和string.Join

轻松完成
var joinedNames = string.Join(", ", fields.Select(f => "\"" + f + "\""));

答案 2 :(得分:3)

var list = new List<string> { "One", "Two", "Three", "Four", "Five", "Six" };
joinedNames = "\"" + string.Join("\", \"", list) + "\"";

答案 3 :(得分:2)

使用string.Join

var myList = new List<string> { "One", "Two", "Three", "Four", "Five", "Six" };
var joined = string.Join(", ", myList.Select(item => "\"" + item + "\""));

答案 4 :(得分:0)

List<string>只是IEnumerable接口的一个实现,它本身就是一个包装器,并继承了string[]的方法,其中有一个string.join(...)方法,这就是你实际上想做。

我使用原始数据运行了测试,但是我在集合中添加了 null 。所有4个版本的数据(列表,数组和每个版本的IEnumerable)都按预期执行了连接方法,最后得到了完全相同的字符串。

    List<string> list = new List<string> { "One", "Two", "Three", null, "Four", "Five", "Six" };
    string JoinedList = "\"" + string.Join("\", \"", list) + "\"";

    string[] array = new string[] { "One", "Two", "Three", null, "Four", "Five", "Six" };
    string JoinedArray = "\"" + string.Join("\", \"", array) + "\"";

    IEnumerable<string> ieList = new List<string> { "One", "Two", "Three", null, "Four", "Five", "Six" };
    string ieListString = "\"" + string.Join("\", \"", ieList) + "\"";


    IEnumerable<string> ieArray = new string[] { "One", "Two", "Three", null, "Four", "Five", "Six" };
    string ieArrayString = "\"" + string.Join("\", \"", ieArray) + "\"";

    Console.WriteLine("Joined List    : " + JoinedList);
    Console.WriteLine("Joined Array    : " + JoinedArray);
    Console.WriteLine("Joined ieList    : " + ieListString);
    Console.WriteLine("Joined ieArray    : " + ieArrayString);

    // results in
    //    Joined List     : "One", "Two", "Three", "", "Four", "Five", "Six"
    //    Joined Array    : "One", "Two", "Three", "", "Four", "Five", "Six"
    //    Joined ieList   : "One", "Two", "Three", "", "Four", "Five", "Six"
    //    Joined ieArray  : "One", "Two", "Three", "", "Four", "Five", "Six"

在您提供的上下文中,任何数据对象都没有优势也没有劣势。如果我们正在寻找性能(无论多么微不足道),我们希望保持字符串[],但如果我们需要最大功能,我们需要使用List。 IEnumerable确实有一些添加的方法(例如Order)但没有Remove函数(以捕获我插入的空值)