07.C#中如何排除/过滤/清空/删除掉字符串数组中的空字符串
方式一:使用lambda表达式筛选过滤掉数组中空字符串
/// <summary> /// 使用lambda表达式排除/过滤/清空/删除掉字符串数组中的空字符串 /// </summary> /// <param name="args"></param> static void Main(string[] args) { string[] strArray = { "","111","","222","","333"}; Console.WriteLine("输出带有空字符串的数组:"); foreach (string str in strArray) { Console.WriteLine(str); } Console.WriteLine("-------------------------------------------"); //使用lambda表达式过滤掉空字符串 strArray = strArray.Where(s=>!string.IsNullOrEmpty(s)).ToArray(); Console.WriteLine("输出过滤掉空字符串的数组:"); foreach (string str in strArray) { Console.WriteLine(str); } Console.Read(); }
方式二:使用泛型集合List<string>的ForEach循环,过滤获取正确的字符串,重新添加到新字符串数组中
string[] strArray = { "", "111", "", "222", "", "333" }; Console.WriteLine("输出带有空字符串的数组:"); foreach (string str in strArray) { Console.WriteLine(str); } Console.WriteLine("-------------------------------------------"); /* *使用List泛型集合的ForEach方法循环获取非空空字符串 *这里使用了匿名方法 */ List<string> list = new List<string>(); strArray.ToList().ForEach( (s) => { if (!string.IsNullOrEmpty(s)) { list.Add(s); } } ); strArray = list.ToArray(); Console.WriteLine("输出过滤掉空字符串的数组:"); foreach (string str in strArray) { Console.WriteLine(str); } Console.Read();
方式三:使用传统循环方式来排除和删除字符串数组中的空字符串
string[] strArray = { "", "111", "", "222", "", "333" }; Console.WriteLine("输出带有空字符串的数组:"); foreach (string str in strArray) { Console.WriteLine(str); } Console.WriteLine("-------------------------------------------"); //使用循环排除和过滤掉空字符串 List<string> list = new List<string>(); foreach (string s in strArray) { if (!string.IsNullOrEmpty(s)) { list.Add(s); } } strArray = list.ToArray(); Console.WriteLine("输出过滤掉空字符串的数组:"); foreach (string str in strArray) { Console.WriteLine(str); } Console.Read();