Home > database >  How to remove empty strings from c# array?
How to remove empty strings from c# array?

Time:06-15

I am removing values with less than 8 characters from an array, but empty strings still remain. How to get rid of them?

for (int i = 0; i < reportbOR.Length; i  )
{
    border = "border:"  reportbOR[i].colorborder;
    string[] text_arr = border.Split('\n');

    foreach (var item in text_arr)
    {
        if (item.Length < 8)
            border = border.Replace(item, "");
    }
}

CodePudding user response:

try this

list = list.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();

CodePudding user response:

You can use the overload of string.Split which accepts a StringSplitOptions enum:

string[] text_arr = border.Split(new string[] { "\n" },
  StringSplitOptions.RemoveEmptyEntries);

Since it's unclear as to when you are having issues removing the empty entries, and you are also replacing strings with 8 or less characters with empty strings, you can use Linq:

text_arr = text_arr.Where(a => !string.IsNullOrWhitespace(a)).ToArray();

You can read about the overload here: stringsplitoptions

And here: string.split

CodePudding user response:

Something like this?

for (int i = 0; i < reportbOR.Length; i  )
{
    var strings = $"border:{reportbOR[i].colorborder}"
        .Split(Environment.NewLine)
        .Where(str => str.Length > 8);

    border = string.Join(Environment.NewLine, strings);
}

CodePudding user response:

You could filter out null, white space, and character length with a couple of different approaches. We will start similar to your above code.

var border = new List<string>();
for(var index = 0; index < reportbOR.Length; index  )
      if(!String.IsNullOrEmpty(reportbOR[index].colorBorder) && reportbOR[index].colorBorder.Length < 8)
           border.Add($"border: {reportbOR[index]}");

I won't mention the StringSplitOptions because of @NSevens response, the documentation is pretty self explanatory but could be applicable.

One thing to denote, if you use LINQ on a String it will parse into a character array. But if you use your root object you could leverage LINQ.

var borders = reportbOR
      .Where(property => !String.IsNullOrEmpty(property.colorBorder) && property.colorBorder < 8))
      .Select(property => new $"border: {property}");

Also, it would be important to know that if you only care about null or empty, then use IsNullOrEmpty. If you want to sanitize for white-space and white-space characters then use IsNullOrWhiteSpace.

  •  Tags:  
  • c#
  • Related