Linq TO SQL 虽好,但不要滥用
生活随笔
收集整理的這篇文章主要介紹了
Linq TO SQL 虽好,但不要滥用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看看下面的例子。我們的場景是,需要對客戶表按照國家進行分組,然后打印出來每個國家的客戶數目。
下面的語法看起來很優雅
using System; using System.Linq;namespace ConsoleApplication1 {class Program{static void Main(string[] args){using (NorthwindDataContext context = new NorthwindDataContext()) {context.Log = Console.Out;var query = from c in context.Customersgroup c by c.Country;foreach (var item in query){Console.WriteLine(string.Format("國家:{0},客戶總數:{1}",item.Key,item.Count()));foreach (var i in item){Console.WriteLine("\t" + i.CustomerID);}}}}} }但是,注意觀察一下,每循環一個國家的時候,又會發起另外一個查詢。這對于數據庫服務器而言,是一個不小的壓力
?
為了做改進,考慮到客戶數據本身也不是很多,我們直接將需要的數據先讀取到內存中,再用LINQ TO Object的方式對其進行出來豈不是更好
using System; using System.Linq;namespace ConsoleApplication1 {class Program{static void Main(string[] args){using (NorthwindDataContext context = new NorthwindDataContext()) {context.Log = Console.Out;var customers = context.Customers.Select(c => new { c.CustomerID, c.Country }).ToArray();var query = from c in customersgroup c by c.Country;foreach (var item in query){Console.WriteLine(string.Format("國家:{0},客戶總數:{1}", item.Key, item.Count()));foreach (var i in item){Console.WriteLine("\t" + i.CustomerID);}}}}} }?
轉載于:https://www.cnblogs.com/chenxizhang/archive/2010/01/07/1641578.html
總結
以上是生活随笔為你收集整理的Linq TO SQL 虽好,但不要滥用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 巧用httpModules实现网站域名更
- 下一篇: SQL Server2005重装Perf