Using LINQ to Query DataTables
By Tan Lee Published on Dec 10, 2024 298
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.
- C# LINQ Tutorial
- C# LINQ query and method syntax
- Group by in LINQ
- How to get the index of an element in C# LINQ
- Cannot use a lambda expression as an argument to a dynamically dispatched operation
- How to group by multiple columns using LINQ
- Using LINQ to remove elements from a List<T>
- How to Find XML element by name with XElement in LINQ
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Carpatin Admin Dashboard Template
Nov 15, 2024
Focus Admin Dashboard Template
Nov 18, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024