Split a comma separated string while removing whitespace and empty entries Split a comma separated string while removing whitespace and empty entries arrays arrays

Split a comma separated string while removing whitespace and empty entries


Using Trim with StringSplitOptions.RemoveEmptyEntries doesn't work because " " isn't considered an empty entry. You need to do a normal split, then trim each item, then filter out the empty strings.

valueString.Split(',')    .Select(x => x.Trim())    .Where(x => !string.IsNullOrWhiteSpace(x))    .ToArray();


Building on the answer from Anthony, this will convert it back to a comma delimited string as well:

valueString = string.Join(",", valueString.Split(',')    .Select(x => x.Trim())    .Where(x => !string.IsNullOrWhiteSpace(x))    .ToArray())


Try this, it works on mine....

item.Split({"|"}, StringSplitOptions.RemoveEmptyEntries)