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

前端 未结 9 563
花落未央
花落未央 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:16
    String.Join(",", array.Where(w => !string.IsNullOrEmpty(w));
    
    0 讨论(0)
  • 2020-12-28 12:18

    A simple solution would be to use linq, by filtering out the empty items before joining.

    // .net 3.5
    string.Join(",", array.Where(item => !string.IsNullOrEmpty(item)).ToArray());
    

    In .NET 4.0 you could also make use of string.IsNullOrWhiteSpace if you also want to filter out the items that are blank or consist of white space characters only (note that in .NET 4.0 you don't have to call ToArray in this case):

    // .net 4.0
    string.Join(",", array.Where(item => !string.IsNullOrWhiteSpace(item)));
    
    0 讨论(0)
  • 2020-12-28 12:28

    Try this :):

    var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
    

    This will join only the strings which is not null or "".

    0 讨论(0)
  • 2020-12-28 12:33
    string.Join(",", Array.FindAll(array, a => !String.IsNullOrEmpty(a)));
    

    How about this one? Cons and pros comparing to LINQ solution? At least it shorter.

    0 讨论(0)
  • 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<string> 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);
    
    0 讨论(0)
  • 2020-12-28 12:38

    Regular expression solution:

    yourString = new Regex(@"[,]{2,}").Replace(yourString, @",");
    
    0 讨论(0)
提交回复
热议问题