gpt4 book ai didi

C# 为什么这个循环这么慢?

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:31 26 4
gpt4 key购买 nike

我继承了一些将过滤器应用于数据网格的代码,该过滤器适用于但当数据网格中有 500 多行时速度非常慢(它挂起超过 500,适用于 100 行),过滤器基本上说“让我看到所有已经付款的人”或“让我看到 X 国家的每个人”等等。

立即创建与过滤器(下面的 filteredRows)匹配的行列表。

        if (comboBoxFilterCondition.Text == "Contains")
{
strSearchFilter += string.IsNullOrEmpty(txtFilterValue.Text) ? " IS NULL" : " LIKE '%" + txtFilterValue.Text + "%'";
}

FilterRows(strSearchFilter);

//....

    private void FilterRows(string strSearchFilter)
{
DataTable table = dataGridView1.DataSource as DataTable;
if (table != null)
{
List<DataRow> filteredRows = new List<DataRow>(table.Select(strSearchFilter)); //<----Very quick to here

CurrencyManager cm = (CurrencyManager)BindingContext[dataGridView1.DataSource];
cm.SuspendBinding();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Visible = filteredRows.Contains(((DataRowView)row.DataBoundItem).Row); //<---Stuck here
}
cm.ResumeBinding(); //<----------Doesn't arrive here

//.....

有什么想法吗?谢谢大家

最佳答案

没有理由自己进行过滤。如果 datagridview 绑定(bind)到 DataTable(看起来确实如此),只需使用 DataTable.DefaultView.RowFilter属性(property)。 sample 来了...

好的,我创建了一个带有 DataGridView 和两个按钮的简单表单。在第一个按钮上单击它应用一个数据表,在第二个按钮上它过滤它:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Age", typeof(int));
table.Rows.Add("John", 25);
table.Rows.Add("Jack", 34);
table.Rows.Add("Mike", 17);
table.Rows.Add("Mark", 54);
table.Rows.Add("Frank", 37);

this.dataGridView1.DataSource = table;
}

private void button2_Click(object sender, EventArgs e)
{
var table = this.dataGridView1.DataSource as DataTable;
table.DefaultView.RowFilter = "Age > 30";

}

当您点击第二个按钮时,网格将被自动过滤。这应该比您自己手动操作快得多。看看我之前给你看的那个链接,还有这个:http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx有关构建过滤器表达式的更多信息。

关于C# 为什么这个循环这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com