Converting SQL to LINQ – DISTINCT, WHERE, ORDER BY and Operators

Bill Horst continues with those simple examples. After this one here comes the other set. They are perfect to show basic syntax. Here are few more:

DISTINCT
SQL SELECT statements can include the DISTINCT specifier, which causes all duplicate records in the query result to be removed. In a LINQ expression, Distinct is its own individual clause, rather than a specifier on the Select clause. This means that Distinct can appear between any two other clauses. The Distinct clause takes whatever result is returned by the preceding clause (Select, in the case below) and returns a filtered result with duplicates removed. To two code examples below accomplish the same results:

SQL

VB

ORDER BY
The SQL ORDER BY clause can also be represented in a LINQ expression. A LINQ Order By clause allows for a comma-delimited list of expressions to specify how results should be sorted. Any valid VB expression can be used, so these expressions don’t necessarily have to be the names of field that were selected.

SQL

VB

ASC/DESC
A SQL ORDER BY clause can also include ASC and DESC keywords, to specify that the sort should be in ascending or descending order, respectively. VB uses Ascending and Descending keywords for the same purpose, with the same syntax. If neither specifier is present, ascending order is the default.

SQL

VB

Here is the original post by Bill Horst


3 thoughts on “Converting SQL to LINQ – DISTINCT, WHERE, ORDER BY and Operators

  1. In Linq we obtain distinct results by using the following syntax (in C#):

    var DistinctResults = (from c in CustomerTable select c.Name).Distinct()

Leave a Reply

Your email address will not be published. Required fields are marked *