如何使用 LINQ 从字符串数组中删除“NULL 行”?
采用这种结构(String[,]
):
"Hello", "World", "Foo", "Bar"
null, null, null, null
null, null, null, null
"Hello", "World", "Foo", "Bar"
"Hello", "World", "Foo", "Bar"
null, null, "Foo", "Bar"
第一行之后的两行应该被删除。结构中的最后一行不应该。
最佳答案
例如,如果您在列表中有数组,您可以这样做:
IList<string[]> l = new List<string[]>
{
new []{ "Hello", "World", "Foo", "Bar" },
new string[]{ null, null, null, null },
new string[] { null, null, null, null },
new [] { "Hello", "World", "Foo", "Bar" },
new [] {null, null, "Foo", "Bar" }
};
var newList = l.Where(a => a.Any(e => e != null));
(更新)
我认为 Linq 不会在多维数组方面为您提供很多帮助。这是一个使用普通旧 for 循环的解决方案...
string[,] arr = new string[,] {
{ "Hello", "World", "Foo", "Bar" },
{ null, null, null, null },
{ null, null, null, null },
{ "Hello", "World", "Foo", "Bar" },
{null, null, "Foo", "Bar" }
};
IList<string[]> l = new List<string[]>();
for (int i = 0; i < arr.GetLength(0); i++)
{
string[] aux = new string[arr.GetLength(1)];
bool isNull = true;
for (int j = 0; j < arr.GetLength(1); j++)
{
aux[j] = arr[i, j];
isNull &= (aux[j] == null);
}
if (!isNull)
l.Add(aux);
}
这导致 List<string[]>
.
关于c# - 使用 LINQ 从字符串数组中删除 "NULL rows",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1939293/