您可以使用 LINQ 创建临时数据表以用作数据源。
建立客户表:
DataTable Customer = new DataTable();
Customer.Columns.Add("CustomerID");
Customer.Columns.Add("Name");
DataRow Stefan = Customer.NewRow();
Stefan["CustomerID"] = 1;
Stefan["Name"] = "Stefan";
Customer.Rows.Add(Stefan);
DataRow Robert = Customer.NewRow();
Robert["CustomerID"] = 2;
Robert["Name"] = "Robert";
Customer.Rows.Add(Robert);
DataRow William = Customer.NewRow();
William["CustomerID"] = 3;
William["Name"] = "William";
Customer.Rows.Add(William);
构建客户表:
DataTable Client = new DataTable();
Client.Columns.Add("ClientID");
Client.Columns.Add("CustomerID");
Client.Columns.Add("Enabled");
DataRow Client1 = Client.NewRow();
Client1["ClientID"] = 1;
Client1["CustomerID"] = 1;
Client1["Enabled"] = true;
Client.Rows.Add(Client1);
DataRow Client2 = Client.NewRow();
Client2["ClientID"] = 2;
Client2["CustomerID"] = 2;
Client2["Enabled"] = true;
Client.Rows.Add(Client2);
DataRow Client3 = Client.NewRow();
Client3["ClientID"] = 3;
Client3["CustomerID"] = 2;
Client3["Enabled"] = false;
Client.Rows.Add(Client3);
DataRow Client4 = Client.NewRow();
Client4["ClientID"] = 4;
Client4["CustomerID"] = 3;
Client4["Enabled"] = false;
Client.Rows.Add(Client4);
过滤客户端表以启用 = false:
BindingSource ClientBS = new BindingSource();
ClientBS.DataSource = Client;
ClientBS.Filter = "Enabled = false";
使用 LINQ 连接这两个表并仅返回带有禁用客户端的客户行:
var CustomersWithDisabledClients = from client in Client.AsEnumerable()
from customer in Customer.AsEnumerable()
where Convert.ToInt32(customer["CustomerID"]) == Convert.ToInt32(client["CustomerID"]) &&
Convert.ToBoolean(client["Enabled"]) == false
select new { CustomerID = customer["CustomerID"], Name = customer["Name"] };
克隆客户表并添加禁用客户的客户行以与您的绑定源一起使用:
DataTable filteredCustomer = Customer.Clone();
CustomersWithDisabledClients.ToList().ForEach(r => filteredCustomer.Rows.Add(r));