C# 通过DataGridViewRowCollection或DataGridViewSelectedRowCollection循环

C# 通过DataGridViewRowCollection或DataGridViewSelectedRowCollection循环,c#,winforms,datagridview,C#,Winforms,Datagridview,我想循环使用DataGridViewRowCollection或DataGridViewSelectedRowCollection(用户选择)。我不知道怎样才能用简单的方法来做。这是我的密码: List<DataGridViewRow> rows = new List<DataGridViewRow>(); if (dr == DialogResult.No) foreach (DataGridViewRow row in dgvResult.Rows)

我想循环使用DataGridViewRowCollection或DataGridViewSelectedRowCollection(用户选择)。我不知道怎样才能用简单的方法来做。这是我的密码:

List<DataGridViewRow> rows = new List<DataGridViewRow>();

if (dr == DialogResult.No)
    foreach (DataGridViewRow row in dgvResult.Rows)
        rows.Add(row);
else if (dr == DialogResult.Yes)
    foreach (DataGridViewRow row in dgvResult.SelectedRows)
        rows.Add(row);

int counter = 1;

foreach (DataGridViewRow row in rows)
{
    //...
}
列表行=新列表();
if(dr==DialogResult.No)
foreach(dgvResult.Rows中的DataGridViewRow行)
行。添加(行);
else if(dr==DialogResult.Yes)
foreach(dgvResult.SelectedRows中的DataGridViewRow行)
行。添加(行);
int计数器=1;
foreach(DataGridViewRow行中的行)
{
//...
}
您可能需要一种方法

List lst=dataGridView1.Rows.Cast().ToList();

您可以创建一个简单数组,并使用两个集合的CopyTo方法

DataGridViewRow[] data;
if (<your condition here>) {
  data=new DataGridViewRow[dvgResult.Rows.Count];
  dvgResult.Rows.CopyTo(data,0);
} else {
  data=new DataGridViewRow[dvgResult.SelectedRows.Count];
  dvgResult.SelectedRows.CopyTo(data,0);
}
//Do whatever you want with 'data', it's a simple array now.
DataGridViewRow[]数据;
如果(){
数据=新的DataGridViewRow[dvgResult.Rows.Count];
dvgResult.Rows.CopyTo(数据,0);
}否则{
数据=新的DataGridViewRow[dvgResult.SelectedRows.Count];
dvgResult.SelectedRows.CopyTo(数据,0);
}
//用“数据”做任何你想做的事情,现在它是一个简单的数组。
当然,它们都是System.Windows.Forms.BaseCollection,您也可以使用BaseCollection的方法

BaseCollection data=<your condition>?dvgResults.Rows:dvgResults.SelectedRows;
//Just enumerate through BaseCollection..
BaseCollection数据=?dvgResults.Rows:dvgResults.SelectedRows;
//只需通过BaseCollection枚举。。

将“System.Windows.Forms.DataGridViewRowCollection”转换为“System.Collections.Generic.IEnumerable”@it-west.net时出错不要忘记使用System.Linq包含
在源文件的顶部,您还可以对
DataGridViewRow
进行更改,由于
DataGridView
的性质,这些更改将自动反映回底层的
DataRow
。DataGridViewSelectedRowCollection的可能重复项确实源自BaseCollection。但是,DataGridViewRowCollection没有。
DataGridViewRow[] data;
if (<your condition here>) {
  data=new DataGridViewRow[dvgResult.Rows.Count];
  dvgResult.Rows.CopyTo(data,0);
} else {
  data=new DataGridViewRow[dvgResult.SelectedRows.Count];
  dvgResult.SelectedRows.CopyTo(data,0);
}
//Do whatever you want with 'data', it's a simple array now.
BaseCollection data=<your condition>?dvgResults.Rows:dvgResults.SelectedRows;
//Just enumerate through BaseCollection..