How do you use datatable.select() in C#?
In C#, the Select() method of the DataTable is used to retrieve rows that meet specified criteria from the DataTable. It’s syntax is as follows:
DataRow[] rows = dataTable.Select(filterExpression);
The filterExpression, which is a string specifying the filter condition, can include column names, operators, and constant values to determine the rows that meet the condition. For example, the filter condition can be specified using the following method:
- Set the value of a specific column to a certain value.
- Specify that the value of a column is greater than a given value.
- The column value refers to when the value of a specific column is less than a given value.
- The column is set to match a specific value, supporting wildcards.
Here is an example demonstrating how to use the Select() method of a DataTable:
DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Rows.Add(1, "John");
dataTable.Rows.Add(2, "Mary");
dataTable.Rows.Add(3, "Peter");
DataRow[] rows = dataTable.Select("Name = 'Mary'");
foreach (DataRow row in rows)
{
Console.WriteLine("ID: {0}, Name: {1}", row["ID"], row["Name"]);
}
The output is:
ID: 2, Name: Mary
In the example above, we used a filter condition “Name = ‘Mary'” to retrieve rows where the value in the Name column equals “Mary”. We then looped through these rows using a foreach loop and outputted their ID and Name values.