【问题标题】:Selecting Multiple Rows from DataGridView using Linq使用 Linq 从 DataGridView 中选择多行
【发布时间】:2016-03-07 10:31:23
【问题描述】:

我正在尝试从 DataGridView 中选择多行,而不是使用 for-each 循环进行迭代。

我可以使用此代码选择 1 项:

DataGridViewRow row2 =
     (from DataGridViewRow r in dgView.Rows
     where r.Cells["name"].Value.ToString().Equals("Akins Ford")select r).FirstOrDefault();

但是当我尝试选择多行时,使用以下代码:

List<DataGridViewRow> rows2 =
      (from DataGridViewRow r in dgView.Rows
       where r.Cells["status"].Value.ToString().Equals("active")select r);

我遇到了一个错误:

错误 2 无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少演员表?) C:\Software\Json\Json\Form1.cs 188 18 Json

【问题讨论】:

  • 你可以试试,而不是 .FirstOrDefault() 试试 .ToList()?
  • 我得到对象引用未设置为对象的实例。错误
  • 你能试试这个吗....dataGridView1.Rows.Cast&lt;DataGridViewRow&gt;().Where(x =&gt; x.Cells["status"].Value.ToString() == "active").ToList().ForEach(x =&gt; x.Selected = true);

标签: c# linq datagridview


【解决方案1】:

你需要对结果做一个简单的环绕:

List<DataGridViewRow> rows2 =
        new List<DataGridViewRow>
        (from DataGridViewRow r in dgView.Rows
         where r.Cells["status"].Value.ToString().Equals("active")
         select r);

这是因为 linq 代码返回 IEnumerable&lt;T&gt; 而不是 List&lt;T&gt;。但是您可以通过调用适当的构造函数从IEnumerable&lt;T&gt; 创建List&lt;T&gt;

var list = new List<T>(iEnumerable);

为了防止空引用异常,您可能需要进一步改进代码:

List<DataGridViewRow> rows2 =
        new List<DataGridViewRow>
        (from DataGridViewRow r in dgView.Rows
         where r.Cells["status"]?.Value.ToString().Equals("active")??false
         select r);

我假设您使用的是允许空传播的 VS2015

r.Cells["status"]?.Value.ToString().Equals("active")??false

把“?”在Cells["status"] 之后确保任何空引用都会导致空值。然后最后的 ??false 说,如果我们有一个 null 我们返回 false(即不包括这一行)。

【讨论】:

  • 或者直接使用ToList
  • 代码编译,但出现以下错误:对象引用未设置为对象的实例。
  • 你可能在 where 子句中有一个例外。 Cell的值是否可以为null?
  • 是的,我确实有一行可以为空 - 修复了它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多