Linq group by, XElement

            if (System.IO.File.Exists(this.textBox1.Text.Trim()) == false)
            {
                MessageBox.Show("文件不存在!"); return;
            }
            //法2
            XElement globalXmlElement = XElement.Load(this.textBox1.Text.Trim());
            var q = from c in globalXmlElement.Elements("errorInfo")
                    group c by c.FirstAttribute.Value into g
                    where g.Count()>1
                    select new 
                    {
                        Code = g.Key,
                        Cnt =g.Count(),
                    };
           
            /*法1
            List < ErrInfo> infosList = (from c in globalXmlElement.Elements("errorInfo")
                        select new ErrInfo { 
                         Code=c.FirstAttribute.Value,
                         Msg=c.LastAttribute.Value,
                        }).ToList < ErrInfo>();
            var q = from i in infosList
                      group i by i.Code into g
                      where g.Count()>1
                      select new {
                          Code=g.Key,
                          Cnt =g.Count(),
                      };
            */
            this.txtResult.Text = string.Empty;
            int cnt = 0;
            foreach (var c in q)
            {
                cnt++;
                this.txtResult.Text +="Code: "+ c.Code +"\t,Cnt= "+c.Cnt+ Environment.NewLine;
            }
            MessageBox.Show("done! Total:"+cnt.ToString());
            
posted @ 2011-05-09 13:55  庚武  Views(408)  Comments(0Edit  收藏  举报