【问题标题】:Remove "NULL rows" from a String array using LINQ使用 LINQ 从字符串数组中删除“NULL 行”
【发布时间】:2009-12-21 10:17:13
【问题描述】:

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

应该删除第一行之后的两行。结构中的最后一行不应该。

【问题讨论】:

  • 你所要求的是不可能的。如果要从数组中删除项目,则必须创建一个新数组并复制要保留的项目,即使您使用 LINQ 为您完成。
  • Linq 很难对 [,] 中定义的数组进行迭代。您是否希望在 Linq 中证明它可以完成,或者因为循环是丑陋的代码? Linq 可能不是我们所有问题的答案:)
  • @Mikael Svenson:使用 LINQ 的一行代码比 5-6 行循环更具可读性。
  • @roosteronacid 是的,如果存在这样的单行的话。

标签: c# arrays linq


【解决方案1】:

例如,如果您在 List 中有数组,您可以这样做:

        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&lt;string[]&gt;

【讨论】:

  • 在查询新建的空列表时,会返回空结果...
【解决方案2】:

这是不可能的,数组是固定大小的,你需要一个新的数组,一个列表或集合可以用这种方式删除东西。

数组不能。你需要在这些行中有一些东西。

任何调用类似 toArray() 的解决方案都在构造一个数组,这是您明确要求不要发生的。

【讨论】:

  • 更新了我的问题。我想要的是一个使用 LINQ 的单行代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
相关资源
最近更新 更多