Using LINQ to Query DataTables
By FoxLearn 12/12/2024 1:08:13 AM 57
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.
- How to get index of element in array C# LINQ
- How to get the index of an element in C# LINQ
- Using LINQ's Distinct() on a Specific Property
- Difference Between Select and SelectMany in LINQ
- Group by in LINQ
- How to group by multiple columns using LINQ
- Using LINQ to remove elements from a List<T>
- IEnumerable<T> vs IQueryable<T>
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024