How to convert IEnumerable to one comma separated string?

前端 未结 6 1618
北荒
北荒 2021-01-01 08:20

Say that for debugging purposes, I want to quickly get the contents of an IEnumerable into one-line string with each string item comma-separated. I can do it in a helper met

相关标签:
6条回答
  • 2021-01-01 08:47
    string output = String.Join(",", yourEnumerable);
    

    String.Join Method (String, IEnumerable

    Concatenates the members of a constructed IEnumerable collection of type String, using the specified separator between each member.

    0 讨论(0)
  • 2021-01-01 08:48

    (a) Set up the IEnumerable:

            // In this case we are using a list. You can also use an array etc..
            List<string> items = new List<string>() { "WA01", "WA02", "WA03", "WA04", "WA01" };
    

    (b) Join the IEnumerable Together into a string:

            // Now let us join them all together:
            string commaSeparatedString = String.Join(", ", items);
    
            // This is the expected result: "WA01, WA02, WA03, WA04, WA01"
    

    (c) For Debugging Purposes:

            Console.WriteLine(commaSeparatedString);
            Console.ReadLine();
    
    0 讨论(0)
  • 2021-01-01 08:51
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class C
    {
        public static void Main()
        {
            var a = new []{
                "First", "Second", "Third"
            };
    
            System.Console.Write(string.Join(",", a));
    
        }
    }
    
    0 讨论(0)
  • 2021-01-01 08:51
    IEnumerable<string> foo = 
    var result = string.Join( ",", foo );
    
    0 讨论(0)
  • 2021-01-01 09:02
    collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");
    
    0 讨论(0)
  • 2021-01-01 09:06

    to join large array of strings to a string, do not directly use +, use StringBuilder to iterate one by one, or String.Join in one shot.

    0 讨论(0)
提交回复
热议问题