I want to remove empty and null string in the split operation:
string number = "9811456789, ";
List<string> mobileNos = number.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(mobile => mobile.Trim()).ToList();
I tried this but this is not removing the empty space entry
var mobileNos = number.Replace(" ", "")
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
As I understand it can help to you;
string number = "9811456789, ";
List<string> mobileNos = number.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
the result only one element in list as [0] = "9811456789".
Hope it helps to you.
a string extension can do this in neat way as below the extension :
public static IEnumerable<string> SplitAndTrim(this string value, params char[] separators)
{
Ensure.Argument.NotNull(value, "source");
return value.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
}
then you can use it with any string as below
char[] separator = { ' ', '-' };
var mobileNos = number.SplitAndTrim(separator);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With