引用:从SQL到LINQ, Part 3: DISTINCT, WHERE, ORDER BY and Operators (Bill Horst)

引用:

从SQL到LINQ, Part 3: DISTINCT, WHERE, ORDER BY and Operators (Bill Horst)

[原文作者]: Bill Horst

[原文链接]: Converting SQL to LINQ, Part 3: DISTINCT, WHERE, ORDER BY and Operators (Bill Horst)

 

在看这篇文章之前,我假定你已经读过了:

SQLLINQPart 1:基础

SQLLINQPart 2FROMSELECT

 

继续我们的话题,这次我将涉及的主题是DISTINCT, WHERE ORDER BY相关的内容。

 

DISTINCT

 

SQLSLECT语句可以指定DISTINCT标识符以去除所有重复的记录。在LINQ表达式里,Distinct不是从属与Select的标识符,而是一个单独的子句-这意味着Distinct可以出现在任意子句后面,并返回去除重复记录前面子句(在下面的例子里是Select)的结果。下面两个语句得到的是相同的结果:

 

SQL

SELECT DISTINCT Name, Address

FROM CustomerTable

 

 

VB

From Contact In CustomerTable _

Select Contact.Name, Contact.Address _

Distinct

 

 

WHERE

 

SQL非常相似,LINQ允许你使用Where子句根据一定的条件筛选记录。你可以使用任意合法的VB布尔表达式。

 

SQL

SELECT * FROM CustomerTable

WHERE State = “WA”

 

 

VB

From Contact In CustomerTable _

Where Contact.State = “WA”

 

 

操作符

 

SQLWHERE子句可以包含AND这样的操作符,LINQ也允许类似的用法。

 

SQL

SELECT * FROM CustomerTable

WHERE City = “Seattle” AND Zip = “98122”

 

 

VB

From Contact In CustomerTable _

Where Contact.City = “Seattle” And Contact.Zip = “98122”

 

 

即使有些操作符不能完全等价,我们仍然可以模拟。例如BETWEEN

 

SQL

SELECT * FROM OrderTable

WHERE OrderDate BETWEEN ‘Sept-22-2007’ AND ‘Sept-29-2007’

 

 

VB

From Shipment In OrderTable _

Where (Shipment.OrderDate > #9/22/2007#) _

    And (Shipment.OrderDate < #9/29/2007#)

 

 

ORDER BY

 

LINQ也提供了类似SQL ORDER BY子句的表达式,它允许我们使用一个由逗号隔开的列表来指定得到结果的排序依据。我们可以使用任意合法的VB表达式,而并不一定要用Select出来的名字。

 

SQL

SELECT * FROM CustomerTable

ORDER BY Phone

 

 

VB

From Contact In CustomerTable _

Order By Contact.Phone

 

 

ASC/DESC

 

SQLORDER BY子句可以使用ASCDESC关键字来指定升序和降序。VB使用的对应的关键字是Ascending Descending,如果没有指定,默认升序。

 

SQL

SELECT * FROM CustomerTable

ORDER BY Phone ASC, Name DESC

 

 

VB

From Contact In CustomerTable _

Order By Contact.Phone Ascending, Contact.Name Descending

 

 

到目前为止,我们应该已经可以将基本的SQL查询写成LINQ代码。下一次,我会谈到函数-包含ScalarAggregate

 

-       Bill Horst, VB IDE Test

你可能感兴趣的:(order by)