Convert `List` to comma-separated string

前端 未结 6 1720
梦毁少年i
梦毁少年i 2020-12-09 00:33

Is there a fast way to convert List to a comma-separated string in C#?

I do it like this but Maybe there is a faster or more

相关标签:
6条回答
  • 2020-12-09 00:58

    The following will result in a comma separated list. Be sure to include a using statement for System.Linq

    List<string> ls = new List<string>();
    ls.Add("one");
    ls.Add("two");
    string type = ls.Aggregate((x,y) => x + "," + y);
    

    will yield one,two

    if you need a space after the comma, simply change the last line to string type = ls.Aggregate((x,y) => x + ", " + y);

    0 讨论(0)
  • 2020-12-09 01:12

    To expand on Jon Skeets answer the code for this in .Net 4 is:

    string myCommaSeperatedString = string.Join(",",ls);
    
    0 讨论(0)
  • 2020-12-09 01:15

    That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

    (does it still work without the ToArray)?

    0 讨论(0)
  • 2020-12-09 01:17

    In .NET 4 you don't need the ToArray() call - string.Join is overloaded to accept IEnumerable<T> or just IEnumerable<string>.

    There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?

    You could iterate over the list, work out the final size, allocate a StringBuilder of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.

    0 讨论(0)
  • 2020-12-09 01:18

    Follow this:

           List<string> name = new List<string>();   
    
            name.Add("Latif");
    
            name.Add("Ram");
    
            name.Add("Adam");
            string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));
    
    0 讨论(0)
  • 2020-12-09 01:24
    static void Main(string[] args)
    {
       List<string> listStrings = new List<string>(){ "C#", "Asp.Net", "SQL Server", "PHP", "Angular"};
       string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
       Console.Write(CommaSeparateString);
       Console.ReadKey();
    }
    
    private static string GenerateCommaSeparateStringFromList(List<string> listStrings)
    {
       return String.Join(",", listStrings);  
    }
    

    Convert a list of string to comma separated string C#.

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