linq group by having 實現


TO XML ,優化的重點還是在細節,細節決定成敗一點也沒錯

 

 

View Code
    System.Diagnostics.Stopwatch st1 =  new System.Diagnostics.Stopwatch();
            st1.Start();
            XDocument xdom = XDocument.Load(XmlPath);
             var restElements = xdom.Descendants( " rest ").ToList();
            st1.Stop();
            HttpContext.Current.Response.Write( " 1.載入XML時間 " + st1.ElapsedMilliseconds +  " <br> ");

 

載入一個大一點的文件,我這里顯示花時間 1700毫秒 左右

 

 

View Code
           System.Diagnostics.Stopwatch st =  new System.Diagnostics.Stopwatch();
            st.Start();
             var Hotels = ( from hotels  in restElements
                           where  
                          hotels.Element( " lat ") !=  null &&  
                          hotels.Element( " lat ").Value !=  string.Empty 
                           select  new
                          {
                              State = hotels.Element( " state ").Value,
                              StateCityKey = (hotels.Element( " state ").Value +  " - " + hotels.Element( " city ").Value).ToUpper()
                          }).ToList();

 

過濾,,生成匿名對象,然后Tolist();這一步的沒什么好說的,關鍵是不要讓他監視XML文件,不要讓他延時加載,生成一個KEY

 

View Code
             var hotelsGroup =
                ( from hotel  in Hotels
                 group hotel by hotel.StateCityKey
                     into h
                      select  new
                     {
                         StateCityKey = h.Key,
                         count = h.Count(),
                         hgrou = h
                     } into c
                      where c.count >  2
                      select c).ToList();
            st.Stop();
            HttpContext.Current.Response.Write( " 2.分組耗費 " + st.ElapsedMilliseconds);
             long a = st1.ElapsedMilliseconds + st.ElapsedMilliseconds;
            HttpContext.Current.Response.Write( " <br>1+2總耗費 : " + a +  " 毫秒<br> ");

 

 分組耗時:40毫秒

通過KEY(StateCityKey)進行分組,注意COUNT,where c.count > 2 對分組以后的數據進行判斷,相當於HAVING

用的不是COUNT() 是count  ,

 

下面的循環統計輸出就不放出來了。。。

 

 轉載請放鏈接 http://www.cnblogs.com/jacd/archive/2012/04/25/2469389.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM