代码之家  ›  专栏  ›  技术社区  ›  Alexander Ryan Baggett

如何使用Linq从DataGridView中检索非空或空白字符串列表

  •  0
  • Alexander Ryan Baggett  · 技术社区  · 12 年前

    当然,我的问题正是我的标题所说的。我对linq还是很陌生的。但它的有用性使我必须学习它。

    我有一个正在进行的查询。我觉得我快到了,但我得到了空列表,尽管DataGridView中有很多名为DataView的内容。

    这是我到目前为止的疑问。

         List<List<string>> newData = new List<List<string>>();
         newData =  DataView.Rows.OfType<DataGridViewRow>()
              .Select(row => row.Cells.OfType<DataGridViewCell>()
                .Select(cell => cell.Value.ToString())
                .Where(s => !string.IsNullOrWhiteSpace(s))
                .ToList()
              .ToList()) as List<List<string>>;
    

    我的询问大致基于我所看到的 here on an MSDN forum.

    1 回复  |  直到 12 年前
        1
  •  1
  •   Grant Winney    12 年前

    LINQ语句返回的实际上是 IEnumerable<List<string>> .

    当您使用 as List<List<string>> ,你的结局是 null …因为结果实际上不是那种类型。

    目前,您已经得到了这个,这是多余的:

    .ToList().ToList()
    

    相应地修改LINQ语句:

    List<List<string>> newData =
        dataGridView1.Rows.OfType<DataGridViewRow>()
                     .Select(row => row.Cells.OfType<DataGridViewCell>()
                                       .Select(cell => cell.Value.ToString())
                                       .Where(s => !string.IsNullOrWhiteSpace(s))
                                       .ToList())
                     .ToList();