c# - 使用 LINQ 从字符串数组中删除 "NULL rows"

标签 c# arrays linq

如何使用 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/

相关文章:

php - 从数组 : for loop not working 返回字母

c# - 使用 LINQ 表达式从集合中获取上一个元素

c# - 如何使用LINQ将List <Int32>中的所有元素选择到另一个List <Int32>中?

c# - 如何在我的 C# WIndows 窗体中附加视频?

C# 以编程方式创建目录快捷方式并不总是有效

c# - 哪个是使用 LINQ 的更好方法?

arrays - 每次以固定常数增长动态数组的效率?

java - 仅对一个数组执行计算时,如何防止两个数组相等?

c# - C# 事件在幕后是如何工作的?

c# - "Does Not Contain"动态lambda表达式