In this example, I will show how to use Linq to query DataTable. A DataTable is a table of data stored in memory. Since Linq can query data of IEnumerable type, the data rows are declared as as IEnumerable so that Linq can query the data.
I have already setup the web application and have added a page. I will now define the schema of the DataTable and then create it. The code for creating the DataTable is below.
As can be seen, columns of type int, string and DateTime are added to the DataTable. Then, rows of data are added. This DataTable is later used for querying using Linq.
As mentioned earlier, to query DataTable using Linq, it has to be of type System.Collections.Generic.IEnumerable . To do this, DataTable’s AsEnumerable method can be used. This method converts the standard DataTable to a DataTable of IEnumerable type. The method for converting and querying the DataTable is below.
At first, I have converted the DataTable to of type IEnumerable and have selected all the rows. Then, I have queried each of the DataRow and retrieved the values for each of the columns. L1 is a Literal control that has been declared on the aspx page.
Please note that, I have simply added the values returned in string variables, ideally, a System.Text.StringBuilder object should be used to achieve this.
The above methods can then be called from Page_Load or other methods as shown below.