-3

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

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
4

6 回答 6

4

一点 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

于 2012-12-03T11:13:02.937 回答
2

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

var array = arraySource.Where(n=> !string.IsNullOrEmpty(n)).ToArray();
于 2012-12-03T10:30:09.723 回答
1

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

string[] newArray = stringArray.Where(r => !r.Equals("null", StringComparison.InvariantCultureIgnoreCase))
                             .ToArray();
于 2012-12-03T10:26:50.133 回答
1

这是一个执行您想要的循环的循环:

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<string>();
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;
        }
    }
}

它在由 string 确定的指定索引处将带有空格的字符串连接起来null

于 2012-12-03T10:54:02.887 回答
0

你可以试试这些线路

string[] myArray = new[] { "Stack", null, "OverFlow" };
string[] nulless = myArray.Where(t => !string.IsNullOrEmpty(t)).ToArray();
于 2012-12-03T10:31:30.627 回答
0

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

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> 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));
        }
于 2012-12-03T10:33:15.640 回答