Introduction
This article will demonstrate the basics for querying a DataSet with LINQ. We would be using XML as the datasource for this application.
Background
Basic understanding of ASP.NET, XML, DataSet and LINQ is desirable.
Using the code
XMLFile.xml (Our data source):
We would be using this XML file as the data source / database for our application.
="1.0" ="utf-8"
<DataSet>
<Employee>
<EmployeeID>1</EmployeeID>
<Name>Sam</Name>
<Age>25</Age>
</Employee>
<Employee>
<EmployeeID>2</EmployeeID>
<Name>Smith</Name>
<Age>21</Age>
</Employee>
<Employee>
<EmployeeID>3</EmployeeID>
<Name>Miller</Name>
<Age>32</Age>
</Employee>
<Employee>
<EmployeeID>5</EmployeeID>
<Name>Mark</Name>
<Age>45</Age>
</Employee>
</DataSet>
Default.aspx
This is the ASPX file for our web application.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ASPNETWebApplication._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Default.aspx.cs
This is our source (C#) file for the application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace ASPNETWebApplication
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Data.DataSet ds = new System.Data.DataSet();
ds.ReadXml(Server.MapPath("~/XMLFile.xml"));
var query = from a in ds.Tables[0].AsEnumerable()
where a.Field<string>("Name") == "Miller"
select a;
foreach (var EmpID in query)
{
Response.Write(EmpID["Name"] + "'s Employee ID - " + EmpID["EmployeeID"].ToString());
}
}
}
}
Explanation
Here we firstly declare and object of DataSet and then we read the XML file into the Data Set.
Here our objective is to find the Employee ID of Employee named "Miller" from the DataSet using LINQ.
Then we execute a LINQ query and get the results into the "query" variable. As the result is in the form of a resultset, for individually getting the records we declare an Object EmpID of type query and loop through the records to get the results.
History
Next update would include more about DataSet and LINQ.