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

前端 未结 9 564
花落未央
花落未央 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:41

    Extension method:

    public static string ToStringWithoutExtraCommas(this object[] array)
    {
        StringBuilder sb = new StringBuilder();
        foreach (object o in array)
        {
    
            if ((o is string && !string.IsNullOrEmpty((string)o)) || o != null)
                sb.Append(o.ToString()).Append(",");
        }
    
        sb.Remove(sb.Length - 1, 1);
    
        return sb.ToString();
    }
    
    0 讨论(0)
  • 2020-12-28 12:42

    You could use linq to remove the empty fields.

    var joinedString = String.Join(",", array.Where(c => !string.IsNullOrEmpty(c));
    
    0 讨论(0)
  • string.Join(",", string.Join(",", array).Split({","}, StringSplitOptions.RemoveEmptyEntries));
    

    v('_')V

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