LINQ is such a vast topic that you will be better off learning comprehensively by buying a book on this superb technology. I'd highly recommend Steve Eichert's and Fabrice Marguerie's "LINQ in Action" book available in Amazon.
In this post, I'll provide examples for converting SQL queries into LINQ (in VB.NET and C#).
These samples are taken from VB Team's blog: http://blogs.msdn.com/b/vbteam/archive/tags/converting+sql+to+linq/default.aspx. Since all their samples are in VB.NET, I'll include C# for completeness.
SELECT * Query
SQL
SELECT *LINQ(VB.NET)
FROM CustomerTable
From Contact In CustomerTableLINQ(C#)
from Contact in CustomerTable
select Contact
SELECT Query
SQL
SELECT Name CustomerName, CustomerID IDLINQ(VB.NET)
FROM Customers
From cust In Customers _LINQ(C#)
Select CustomerName = cust.Name, ID = cust.CustomerID _
Order By ID
from cust in Customers
select new(){CustomerName=cust.Name, ID=cust.CustomerID }
SELECT... WHERE Query
SQL
SELECT * FROM CustomerTableLINQ(VB.NET)
WHERE State = “WA”
From Contact In CustomerTable _LINQ(C#)
Where Contact.State = “WA”
from Contact in CustomerTable
where Contact.State=="WA"
select Contact
SELECT DISTINCT Query
SQL
SELECT DISTINCT Name, AddressLINQ(VB.NET)
FROM CustomerTable
From Contact In CustomerTable _LINQ(C#)
Select Contact.Name, Contact.Address _
Distinct
(from Contact in CustomerTable
select new(){Contact.Name,Contact.Address}).Distinct()
AND Operator Query
SQL
SELECT * FROM CustomerTableLINQ(VB.NET)
WHERE City = “Seattle” AND Zip = “98122”
From Contact In CustomerTable _LINQ(C#)
Where Contact.City = “Seattle” And Contact.Zip = “98122”
from Contact in CustomerTable
where Contact.City=="Seattle" && Contact.Zip=="98122"
select Contact
BETWEEN Operator Query
SQL
SELECT * FROM OrderTableLINQ(VB.NET)
WHERE OrderDate BETWEEN ‘Sept-22-2007’ AND ‘Sept-29-2007’
From Shipment In OrderTable _LINQ(C#)
Where (Shipment.OrderDate > #9/22/2007#) _
And (Shipment.OrderDate < #9/29/2007#)
from Shipment in OrderTable
where Shipment.OrderDate > new Date(2007,9,22) &&
Shipment.OrderDate < new Date(2007,9,29)
select Shipment
Order By Query
SQL
SELECT * FROM CustomerTableLINQ(VB.NET)
ORDER BY Phone
From Contact In CustomerTable _LINQ(C#)
Order By Contact.Phone
from Contact in CustomerTable
orderby Contact.Phone
select Contact
Order By ASC/DESC Query
SQL
SELECT * FROM CustomerTableLINQ(VB.NET)
ORDER BY Phone ASC, Name DESC
From Contact In CustomerTable _LINQ(C#)
Order By Contact.Phone Ascending, Contact.Name Descending
from Contact in CustomerTable
orderby Contact.Phone ascending, Contact.Name descending
select Contact
I'll update this blog later and add more samples...
No comments:
Post a Comment