Removing extra commas from string after using String.Join to convert array to string (C#)

前端 未结 9 695
花落未央
花落未央 2020-12-28 12:15

I\'m converting an array into a string using String.Join. A small issue I have is that, in the array some index positions will be blank. An example is below:

9条回答
  •  盖世英雄少女心
    2020-12-28 12:33

    Simple extension method

    namespace System
    {
        public static class Extenders
        {
            public static string Join(this string separator, bool removeNullsAndWhiteSpaces, params string[] args)
            {
                return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args);
            }
            public static string Join(this string separator, bool removeNullsAndWhiteSpaces, IEnumerable args)
            {
                return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args);
            }
        }
    }
    

    Usage:

    var str = ".".Join(true, "a", "b", "", "c");
    //or 
    var arr = new[] { "a", "b", "", "c" };
    str = ".".Join(true, arr);
    

提交回复
热议问题