Remove blank values from array using C#

前端 未结 4 1773
陌清茗
陌清茗 2020-12-13 23:20

How can I remove blank values from an array?

For example:

string[] test={"1","","2","","3"};
<         


        
相关标签:
4条回答
  • 2020-12-13 23:56

    You can use Linq in case you are using .NET 3.5 or later:

     test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
    

    If you can't use Linq then you can do it like this:

    var temp = new List<string>();
    foreach (var s in test)
    {
        if (!string.IsNullOrEmpty(s))
            temp.Add(s);
    }
    test = temp.ToArray();
    
    0 讨论(0)
  • 2020-12-13 23:58

    I prefer to use two options, white spaces and empty:

    test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
    test = test.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
    
    0 讨论(0)
  • 2020-12-14 00:02

    If you are using .NET 3.5+ you could use linq.

    test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

    0 讨论(0)
  • 2020-12-14 00:20

    I write below code to remove the blank value in the array string.

    string[] test={"1","","2","","3"};
    test= test.Except(new List<string> { string.Empty }).ToArray();
    
    0 讨论(0)
提交回复
热议问题