Using LINQ to Query DataTables
By FoxLearn 12/12/2024 1:08:13 AM 148
To perform LINQ queries on a DataTable in C#, you first need to ensure that you are working with LINQ to DataSet, which allows you to query DataTable objects using LINQ syntax.
How to Perform LINQ Queries on a DataTable in C#?
For this example, let’s create a DataTable
and populate it with some sample data.
var dt = new DataTable("Person"); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Age", typeof(int)); // Add some rows to the DataTable dt.Rows.Add(1, "Alice", 30); dt.Rows.Add(2, "Bob", 25); dt.Rows.Add(3, "Charlie", 35); dt.Rows.Add(4, "David", 28);
Now, you can use LINQ queries to query the DataTable
.
For example, if you want to retrieve all the rows where the age is greater than 30:
var rows = from o in dt.AsEnumerable() where o.Field<int?>("Age") > 30 orderby o.Field<int?>("Age") descending select o; foreach (var row in rows) Console.WriteLine($"ID: {row.Field<int>("ID")}, Name: {row.Field<string>("Name")}, Age: {row.Field<int?>("Age")}");
Output:
ID: 3, Name: Charlie, Age: 35
You can also use method syntax to achieve the same results. For example, retrieving names where the age is under 30:
var rows = dt.AsEnumerable() .Where(row => row.Field<int?>("Age") < 30) .Select(row => new { ID = row.Field<int>("ID"), Name = row.Field<string>("Name"), Age = row.Field<int>("Age") });
The DataTable
class doesn’t directly support LINQ queries, which is why we need to use the AsEnumerable()
method to enable LINQ querying.
Categories
Popular Posts
How to secure ASP.NET Core with NWebSec
11/07/2024
Material Lite Admin Template
11/14/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
tsParticles Authentication Template
11/17/2024