C # concatenates string, but double quote all values ​​inside

I have a list of strings

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

And I want to have a string with the exact content (including double quotes)

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

Because it will write a text file, which will be an array [] = {my_string}

I tried this without success

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

A little LINQ help would be greatly appreciated :)

+4
source share
5 answers
var joinedNames = "\"" + string.Join("\", \"", fields) + "\"";
+12
source

You can do it easily with Linq and string.Join

var joinedNames = string.Join(", ", fields.Select(f => "\"" + f + "\""));
+5
source

string.Join:

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

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 ( , )

0

Source: https://habr.com/ru/post/1676281/


All Articles