方式一:使用lambda表达式筛选过滤掉数组中空字符串
1 /// <summary> 2 /// 使用lambda表达式排除/过滤/清空/删除掉字符串数组中的空字符串 3 /// </summary> 4 /// <param name="args"></param> 5 static void Main(string[] args) 6 { 7 string[] strArray = { "","111","","222","","333"}; 8 Console.WriteLine("输出带有空字符串的数组:"); 9 foreach (string str in strArray) 10 { 11 Console.WriteLine(str); 12 } 13 Console.WriteLine("-------------------------------------------"); 14 //使用lambda表达式过滤掉空字符串 15 strArray = strArray.Where(s=>!string.IsNullOrEmpty(s)).ToArray(); 16 Console.WriteLine("输出过滤掉空字符串的数组:"); 17 foreach (string str in strArray) 18 { 19 Console.WriteLine(str); 20 } 21 Console.Read(); 22 }
方式二:使用泛型集合List<string>的ForEach循环,过滤获取正确的字符串,重新添加到新字符串数组中
1 string[] strArray = { "", "111", "", "222", "", "333" }; 2 Console.WriteLine("输出带有空字符串的数组:"); 3 foreach (string str in strArray) 4 { 5 Console.WriteLine(str); 6 } 7 Console.WriteLine("-------------------------------------------"); 8 9 /* 10 *使用List泛型集合的ForEach方法循环获取非空空字符串 11 *这里使用了匿名方法 12 */ 13 List<string> list = new List<string>(); 14 strArray.ToList().ForEach( 15 (s) => 16 { 17 if (!string.IsNullOrEmpty(s)) 18 { 19 list.Add(s); 20 } 21 } 22 ); 23 strArray = list.ToArray(); 24 25 Console.WriteLine("输出过滤掉空字符串的数组:"); 26 foreach (string str in strArray) 27 { 28 Console.WriteLine(str); 29 } 30 Console.Read();
方式三:使用传统循环方式来排除和删除字符串数组中的空字符串
1 string[] strArray = { "", "111", "", "222", "", "333" }; 2 Console.WriteLine("输出带有空字符串的数组:"); 3 foreach (string str in strArray) 4 { 5 Console.WriteLine(str); 6 } 7 Console.WriteLine("-------------------------------------------"); 8 9 //使用循环排除和过滤掉空字符串 10 List<string> list = new List<string>(); 11 foreach (string s in strArray) 12 { 13 if (!string.IsNullOrEmpty(s)) 14 { 15 list.Add(s); 16 } 17 } 18 19 strArray = list.ToArray(); 20 21 Console.WriteLine("输出过滤掉空字符串的数组:"); 22 foreach (string str in strArray) 23 { 24 Console.WriteLine(str); 25 } 26 Console.Read();
原文地址:https://www.cnblogs.com/zhh19981104/p/9692068.html
时间: 2024-10-04 21:49:32