C# - using LINQ to Query DataTable
In this article you will learn how to "walk" through data stored in DataTable using LINQ.
Imagine, you have some movies stored in DataTable like this:
ID Title Year
--- ------------------------------------------- ----------
1 The Lord of the Rings - The Two Towers 2002
2 Forrest Gump 1994
3 Heat 1995
The task is to show only movies created in 1995 and after, and here is the code that does that using LINQ:
// Function LoadMoviesFromDatabase() is our virtual "database"...
DataTable dtMovies = LoadMoviesFromDatabase();
// The trick is here...
var movies = from p in dtMovies.AsEnumerable()
where p.Field<int>("Year") >= 1995
select new
{
ID = p.Field<int>("ID"),
Title = p.Field<string>("Title"),
Year = p.Field<int>("Year")
};
// Writing some output...
foreach (var movie in movies)
{
Console.WriteLine(string.Format("{0}. {1} ({2})", movie.ID, movie.Title, movie.Year));
}
Your output will look like this:
1. The Lord of the Rings - The Two Towers (2002)
3. Heat (1995)
And that's it!
The point is to use your DataTable as Enumerable, where you access strongly-typed columns.
IMPORTANT: be aware that using .Field<int> you cast
the data from that column to specified type - in this case int.
If you cast types that cannot be casted, you will receive "Invalid cast exception".