Converting a List to a comma separated string

后端 未结 8 1417
深忆病人
深忆病人 2020-12-12 23:04

Is there a way to take a List and convert it into a comma separated string?

I know I can just loop and build it, but somehow I think some of you guys a more cool w

相关标签:
8条回答
  • 2020-12-12 23:42

    Seems reasonablly fast.

    IList<int> listItem = Enumerable.Range(0, 100000).ToList();
    var result = listItem.Aggregate<int, StringBuilder, string>(new StringBuilder(), (strBuild, intVal) => { strBuild.Append(intVal); strBuild.Append(","); return strBuild; }, (strBuild) => strBuild.ToString(0, strBuild.Length - 1));
    
    0 讨论(0)
  • 2020-12-12 23:43
    List<int> list = new List<int> { 1, 2, 3 };
    Console.WriteLine(String.Join(",", list.Select(i => i.ToString()).ToArray()));
    
    0 讨论(0)
  • 2020-12-12 23:49
    List<int> list = ...;
    string.Join(",", list.Select(n => n.ToString()).ToArray())
    
    0 讨论(0)
  • 2020-12-12 23:49

    For extra coolness I would make this an extension method on IEnumerable<T> so that it works on any IEnumerable:

    public static class IEnumerableExtensions {
      public static string BuildString<T>(this IEnumerable<T> self, string delim = ",") {
        return string.Join(delim, self)        
      }
    }
    

    Use it as follows:

    List<int> list = new List<int> { 1, 2, 3 };
    Console.WriteLine(list.BuildString(", "));
    
    0 讨论(0)
  • 2020-12-12 23:51

    you can use, the System.Linq library; It is more efficient:

    using System.Linq;
    string str =string.Join(",", MyList.Select(x => x.NombreAtributo));
    
    0 讨论(0)
  • 2020-12-12 23:52

    For approximately one gazillion solutions to a slightly more complicated version of this problem -- many of which are slow, buggy, or don't even compile -- see the comments to my article on this subject:

    https://docs.microsoft.com/en-us/archive/blogs/ericlippert/comma-quibbling

    and the StackOverflow commentary:

    Eric Lippert's challenge "comma-quibbling", best answer?

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