简体   繁体   中英

Selecting Multiple Rows from DataGridView using Linq

I'm trying to select multiple rows from a DataGridView instead of iterating with a for-each loop.

I can select 1 item using this code:

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

But when I try to select multiple rows, using this code:

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

I got an error:

Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) C:\\Software\\Json\\Json\\Form1.cs 188 18 Json

You need to do a simple wrap around the result:

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

This is because the linq code returns an IEnumerable<T> and not List<T> . But you can create a List<T> from an IEnumerable<T> by calling the appropriate constructor:

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

To prevent null reference exceptions you might want to further improve your code thus:

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

I am assuming that you are using VS2015 which allows null propagation

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

putting the '?' after the Cells["status"] ensures that any null references result in a null. And then the final ??false says, that if we had a null we return false (ie don't include this row).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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