string.Join on a List or other type

前端 未结 7 1606
甜味超标
甜味超标 2020-12-01 10:19

I want to turn an array or list of ints into a comma delimited string, like this:

string myFunction(List a) {
    return string.Join(\",\", a);
}
         


        
7条回答
  •  醉话见心
    2020-12-01 10:35

    A scalable and safe implementation of a generic enumerable string join for .NET 3.5. The usage of iterators is so that the join string value is not stuck on the end of the string. It works correctly with 0, 1 and more elements:

    public static class StringExtensions
    {
        public static string Join(this string joinWith, IEnumerable list)
        {
            if (list == null)
                throw new ArgumentNullException("list");
            if (joinWith == null)
                throw new ArgumentNullException("joinWith");
    
            var stringBuilder = new StringBuilder();
            var enumerator = list.GetEnumerator();
    
            if (!enumerator.MoveNext())
                return string.Empty;
    
            while (true)
            {
                stringBuilder.Append(enumerator.Current);
                if (!enumerator.MoveNext())
                    break;
    
                stringBuilder.Append(joinWith);
            }
    
            return stringBuilder.ToString();
        }
    }
    

    Usage:

    var arrayOfInts = new[] { 1, 2, 3, 4 };
    Console.WriteLine(",".Join(arrayOfInts));
    
    var listOfInts = new List { 1, 2, 3, 4 };
    Console.WriteLine(",".Join(listOfInts));
    

    Enjoy!

提交回复
热议问题