[英]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.