linq group by having 实现

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毫秒 左右

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

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>");

通过KEY(StateCityKey)进行分组,注意COUNT,where c.count > 2 对分组以后的数据进行判断,相当于HAVING用的不是COUNT() 是count  

posted @ 2026-03-27 17:25  每天进步多一点  阅读(21)  评论(0)    收藏  举报