DataTable filters certain data

To filter certain data in the DataTable, you can use the following method:

  1. Using the Select method: You can use the Select method of DataTable to filter data rows that meet specified conditions. This method accepts a string parameter as the filter condition and returns an array of data rows that meet the condition.
DataTable filteredTable = originalTable.Select("Column1 = 'value' AND Column2 > 100").CopyToDataTable();

The above code will return a new DataTable object filteredTable, which contains the data rows in the original table that meet the conditions (Column1 is equal to 'value' and Column2 is greater than 100).

  1. Query using LINQ: If you are familiar with LINQ syntax, you can also use LINQ to filter the DataTable. By using the Where method and Lambda expression, you can filter out data rows that meet the conditions.
var filteredRows = originalTable.AsEnumerable()
                        .Where(row => row.Field<string>("Column1") == "value" && row.Field<int>("Column2") > 100);

DataTable filteredTable = filteredRows.Any() ? filteredRows.CopyToDataTable() : originalTable.Clone();

The above code will return a new DataTable object filteredTable, which contains the data rows in the original table that meet the conditions (Column1 is equal to 'value' and Column2 is greater than 100). If there are no data rows that meet the condition, an empty DataTable is returned, but the table structure is the same as the original table.

The above are two commonly used methods to filter data in DataTable. Depending on your specific needs, you can choose a suitable method to implement data filtering.

Guess you like

Origin blog.csdn.net/qq_41177135/article/details/132058037