C# – Remove “NULL rows” from a String array using LINQ

arraysclinq

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", "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.

Best Answer

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[]>.