Search code examples
c#datatabledataview

C# Filter DataTable with multiple keys (columns) and multiple values


I have a table with three columns A, B and C, where A, B are the keys and C is the corresponding value.

I've trying to filter it with multiple values for the keys. In order to do that, I've tried:

// Initialise some data
DataTable dt = new DataTable();
dt.Columns.Add("A", typeof(int));
dt.Columns.Add("B", typeof(int));
dt.Columns.Add("C", typeof(string));

dt.Rows.Add(1, 1, "temp1");
dt.Rows.Add(1, 2, "temp2");
dt.Rows.Add(2, 1, "temp3");
dt.Rows.Add(2, 2, "temp4");

dgv1.DataSource = dt;

// Filter the DataTable to show the second and third lines of `dt`
DataView dv = new DataView(dt);
dv.RowFilter = "(A = 1 and B = 2) and (A = 2 and B = 1)";
dgv2.DataSource = dv;

After the RowFilter, the dv is empty. But I was expecting to receive the second and third lines from the DataTable.

If I do:

dv.RowFilter = "(A = 1 and B = 2)";

it filters fine, but it shows just one line (not what I really need).

Does anyone know how to filter a DataTable with multiple values and multiple keys?

Thanks!


Solution

  • If I understand correctly, you can use dv.RowFilter = "((A = 1 and B = 2) or (A = 2 and B = 1))"

    The reason your original filter was not giving you any results, is because A can't = 1 AND 2, likewise with B. What you are looking for is one OR the other.