What is the usage of datatable select in C#?
The DataTable class in C# offers a Select method that allows you to select rows that meet specified criteria from the DataTable.
The syntax of the Select method is as follows:
public DataRow[] Select(string filterExpression);
The filterExpression parameter, which is a string, is used to specify the filtering criteria. It supports the logical combination of multiple conditions by using operators (such as =, >, <, etc.) and logical operators (such as AND, OR) to create complex conditions.
The sample code is shown below:
DataTable dataTable = new DataTable();
// 假设dataTable中包含以下列:Name(姓名)、Age(年龄)、Gender(性别)
// 选择年龄大于等于18的行
DataRow[] rows = dataTable.Select("Age >= 18");
// 选择姓名为"张三"且性别为"男"的行
DataRow[] rows = dataTable.Select("Name = '张三' AND Gender = '男'");
The Select method returns an array of DataRow containing all rows that meet the conditions. You can access the data of each row by iterating through the array.
Note: When building the filterExpression, make sure to use quotes correctly according to the specific data type. For example, if a column is of string type, wrap the string value in single quotes; if a column is of number type, do not use quotes.