想要从我的数组中检索字符串

我的字符串数组包含以下值

null String 1 String 2 String 3 null String 4 String 5 String 6 null String 7 String 8 String 9 

我想要检索

 String 1 String 2 String 3 String 4 String 5 String 6 String 7 String 8 String 9 

一点LINQ魔术

 var arr = new [] {null,"string1","string2","string3",null,"string4","string5","string6",null,"string7","string8","string9"}; var items = arr.Select( (item,index) => new {item, nextNull = Array.IndexOf(arr,null,index)} ) .GroupBy(x => x.nextNull) .Where(x => x.Any(y => !String.IsNullOrEmpty(y.item))) .Select(x => String.Join(" ",x.Select(y => y.item))); 

输出:

 string1 string2 string3 string4 string5 string6 string7 string8 string9 

实例: http : //rextester.com/GOIT12899

我想null表示意味着一个空字符串:

 var array = arraySource.Where(n=> !string.IsNullOrEmpty(n)).ToArray(); 

如果您的数组中有NULL作为字符串,那么您尝试:

 string[] newArray = stringArray.Where(r => !r.Equals("null", StringComparison.InvariantCultureIgnoreCase)) .ToArray(); 

这是一个完成你想要的循环:

 string[] str = new[] { "null", "String 1", "String 2", "String 3", "null", "String 4", "String 5", "String 6", "null", "String 7", "String 8", "String 9" }; var newStr = new List(); for (int i = 0; i < str.Length; i++) { string current = str[i]; if (current == "null") { int index = Array.IndexOf(str, "null", i + 1, str.Length - (i + 1)); if (index >= 0) { newStr.Add(string.Join(" ", str.Skip(i + 1).Take(index - 1 - i))); i = index - 1; } else { if (i != str.Length - 1) newStr.Add(string.Join(" ", str.Skip(i + 1).Take(str.Length - i))); break; } } } 

它在由字符串null确定的指定索引处连接具有空格的字符串。

将其拆分为已定义的部分,但您需要使用列表:

 public static IEnumerable> Split(this IEnumerable list, int parts) { return list.Select((item, index) => new {index, item}) .GroupBy(x => (x.index + 1) / (list.Count()/parts) + 1) .Select(x => x.Select(y => y.item)); } 

你可以尝试这些线

 string[] myArray = new[] { "Stack", null, "OverFlow" }; string[] nulless = myArray.Where(t => !string.IsNullOrEmpty(t)).ToArray();