Linq TO SQL 虽好,但不要滥用
生活随笔
收集整理的這篇文章主要介紹了
Linq TO SQL 虽好,但不要滥用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
看看下面的例子。我們的場景是,需要對客戶表按照國家進行分組,然后打印出來每個國家的客戶數(shù)目。
下面的語法看起來很優(yōu)雅
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},客戶總數(shù):{1}",item.Key,item.Count()));foreach (var i in item){Console.WriteLine("\t" + i.CustomerID);}}}}} }但是,注意觀察一下,每循環(huán)一個國家的時候,又會發(fā)起另外一個查詢。這對于數(shù)據(jù)庫服務器而言,是一個不小的壓力
?
為了做改進,考慮到客戶數(shù)據(jù)本身也不是很多,我們直接將需要的數(shù)據(jù)先讀取到內(nèi)存中,再用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},客戶總數(shù):{1}", item.Key, item.Count()));foreach (var i in item){Console.WriteLine("\t" + i.CustomerID);}}}}} }?
轉(zhuǎn)載于:https://www.cnblogs.com/chenxizhang/archive/2010/01/07/1641578.html
總結(jié)
以上是生活随笔為你收集整理的Linq TO SQL 虽好,但不要滥用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 巧用httpModules实现网站域名更
- 下一篇: Windows Mobile Incom