Querying LINQ to SQL: Basics - Retrieving DISTINCT values using LINQ
(Page 3 of 6 )
Let us imagine that I have a SELECT query, like the following:
SELECT DISTINCT CustomerID FROM Orders
And now, we will have to represent the same thing using LINQ (in VB). The code is as follows:
Protected Sub btnDistinct_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDistinct.Click
Dim db As New NorthwindDataContext
Dim s As New IO.StringWriter
db.Log = s
Dim q = From p In db.Orders _
Select p.CustomerID Distinct
Me.GridView1.DataSource = q
Me.GridView1.DataBind()
Me.lblGenSQL.Text = s.ToString
End Sub
The same can be accomplished in C# as follows:
protected void btnDistinct_Click(object sender, EventArgs e)
{
NorthwindDataContext db = new NorthwindDataContext();
StringWriter s = new StringWriter();
db.Log = s;
var q = (from p in db.Orders
select p.CustomerID).Distinct() ;
this.GridView1.DataSource = q;
this.GridView1.DataBind();
this.lblGenSQL.Text = s.ToString();
}
What if I have this query:
SELECT DISTINCT CustomerID, EmployeeID FROM Orders
The above query returns all rows with CustomerID and EmployeeID without repetition (combined DISTINCT and not individual DISTINCT). That means CustomerID and EmployeeID can repeat alone, but cannot repeat combined.
To make this possible using LINQ (in VB), the query would be as follows:
Dim q = From p In db.Orders _
Select p.CustomerID, p.EmployeeID Distinct
The same in C# would be as follows:
var q = (from p in db.Orders
select new { p.CustomerID, p.EmployeeID }).Distinct();
Next: Sorting rows with ORDER BY using LINQ >>
More .NET Articles
More By Jagadish Chaterjee