之前有發表過一篇,LINQ的IN與NOT IN,看起來似乎有點麻煩,並不是那麼的好用,那麼小弟再來寫寫IN與NOT IN的簡單用法。(以Northwind的Orders為範例)
1.LINQ - IN
Code:
MyDataContext db = new MyDataContext();
1.LINQ - IN
Code:
MyDataContext db = new MyDataContext();
string[] strArray = new string [] { "ALFKI", "ANATR" };
var result = from c in db.Orders
where strArray.Contains(c.CustomerID)
orderby c.CustomerID ascending
select c;
where strArray.Contains(c.CustomerID)
orderby c.CustomerID ascending
select c;
dataGridView1.DataSource = result.ToList();
SQL Code:
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]
WHERE [t0].[CustomerID] IN (@p0, @p1)
結果:
2.LINQ - NOT IN
Code:
MyDataContext db = new MyDataContext();
SQL Code:
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]
WHERE [t0].[CustomerID] IN (@p0, @p1)
結果:
2.LINQ - NOT IN
Code:
MyDataContext db = new MyDataContext();
string[] strArray = new string[] { "ALFKI", "ANATR" };
var result = from c in db.Orders
where !strArray.Contains(c.CustomerID)
orderby c.CustomerID ascending
select c;
where !strArray.Contains(c.CustomerID)
orderby c.CustomerID ascending
select c;
dataGridView1.DataSource = result.ToList();
SQL Code:
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]
WHERE NOT ([t0].[CustomerID] IN (@p0, @p1))
ORDER BY [t0].[CustomerID]
結果:
是否簡單多了呢!? 看起來確實比之前發的那一篇還要簡單,供大家參考。
SQL Code:
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]
WHERE NOT ([t0].[CustomerID] IN (@p0, @p1))
ORDER BY [t0].[CustomerID]
結果:
是否簡單多了呢!? 看起來確實比之前發的那一篇還要簡單,供大家參考。
沒有留言:
張貼留言