通过 LINQ 从 gridview 获取列值

Get column value from gridview via LINQ

我有使用以下代码从 gridview 接收值的代码:

foreach (GridViewRow gr in MainGridView.Rows)
{

     if (MainGridView.Rows[gr.RowIndex].Cells[1].Text == "Total" || MainGridView.Rows[gr.RowIndex].Cells[0].Text == "Total")
             MainGridView.Rows[gr.RowIndex].Font.Bold = true;
}

它获取其特定单元格包含特定文本的所有行。可以通过 LINQ 实现吗?

I want to get the rows where the particular cells contain the word Total. Is it possible via LINQ?

IEnumerable<GridViewRow> rows = MainGridView.Rows.Cast<GridViewRow>()
    .Where(row => row.Cells[0].Text == "Total" || row.Cells[1].Text == "Total");

或者,更易于维护:

int[] cells = { 0, 1 };
IEnumerable<GridViewRow> rows = MainGridView.Rows.Cast<GridViewRow>()
    .Where(row => cells.Any(c => row.Cells[c].Text == "Total"));

如果你想不区分大小写地比较(也需要 "total"):

.Where(row => cells.Any(c => row.Cells[c].Text.Equals("Total", StringComparison.InvariantCultureIgnoreCase)));

如果您现在想要将所有这些行设为粗体,请使用 foreach:

foreach(var row in rows)
    row.Font.Bold = true;