开发者

Remove "NULL rows" from a String array using LINQ

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

Take this structure (String[,]):

"Hello", "World", "Foo", "Bar"
null,    null,    null,  null
null,    null,    null,  null
"Hello", "Wor开发者_开发知识库ld", "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));

(update)

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

This results in a List<string[]>.


It is not possible to do this, arrays are a fixed size, you would need a new array, a list or collection can have things removed in this manner.

Arrays cannot. You need to have something in those rows.

Any solutions calling something like toArray() are constructing an array which is what you specifically asked not to happen.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜