繁体   English   中英

使用Linq从DataGridView中选择多行

[英]Selecting Multiple Rows from DataGridView using Linq

我正在尝试从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

你需要对结果进行简单的包装:

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

这是因为linq代码返回IEnumerable<T>而不是List<T> 但是您可以通过调用相应的构造函数从IEnumerable<T>创建List<T>

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"]确保任何空引用导致null之后。 然后最终??false说,如果我们有一个null,我们返回false(即不包括这一行)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM