移除];空行"使用LINQ一个String数组 [英] Remove "NULL rows" from a String array using LINQ

查看:177
本文介绍了移除];空行"使用LINQ一个String数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何从一个字符串数组使用LINQ删除空行?

How would you remove "NULL rows" from a String array using LINQ?

把这个结构(字符串[,]

"Hello", "World", "Foo", "Bar"
null,    null,    null,  null
null,    null,    null,  null
"Hello", "World", "Foo", "Bar"
"Hello", "World", "Foo", "Bar"
null,    null,    "Foo", "Bar"

的第一行后两行应被删除。最后一排的结构不应该的。

The two rows after the first row should be removed. The last row in the structure should not.

推荐答案

如果你在一个列表阵列,例如,你可以这样做:

If you have the arrays in a List, for instance, you could do this:

        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循环的解决方案...

I don't think Linq will give you much assistance with multidimensional arrays. Here's a solution using plain old for loops...

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

这导致了列表与LT;字符串[]方式&gt;

这篇关于移除];空行&QUOT;使用LINQ一个String数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆