zoukankan      html  css  js  c++  java
  • 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.Customers
                                group 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);
                        }
                    }
                }
            }
        }
    }
    

    但是,注意观察一下,每循环一个国家的时候,又会发起另外一个查询。这对于数据库服务器而言,是一个不小的压力

    image

    为了做改进,考虑到客户数据本身也不是很多,我们直接将需要的数据先读取到内存中,再用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 customers
                                group 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);
                        }
                    }
                }
            }
        }
    }
    

    image

     
  • 相关阅读:
    《Eric带您走近Office 2010》系列专题来啦!
    以人为本 体验至上(二)
    以人为本 体验至上(一)
    操作Static对象的多线程问题
    TroubleShoot:SilverLight中Wcf调用时出现Not Found等错误
    delegate与event的关系说明
    SharePoint对象模型性能考量
    SharePoint自带Silverlight WebPart中文输入问题处理
    关于Wcf事件多次执行的问题
    SharePoint中调试SilverLight程序
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1641578.html
Copyright © 2011-2022 走看看