日期:2014-05-20  浏览次数:20756 次

linq to xml 分组
需求就是取每个分组中的第一条数据

------解决方案--------------------
C# code

string siteMap = HttpContext.Current.Request.MapPath("Test.xml");
XDoc = XDocument.Load(siteMap);
var thispage = from page in XDoc.Descendants("SitePage")
               where page.Element("Title").Value.ToLower().Contains(strSearchTerm)        
group page by page.Element("Category").Value into g 
orderby g.Count() descending
select page.Element("Title").Value;

------解决方案--------------------
最好把需求说的明白些,别人才好为你更好的解答..
给你一个按照多列分组的例子,希望对你有帮助.
C# code

XDocument doc = XDocument.Load("test.xml");
            var groups =
                from product in doc.Root.Elements("product")
                group product by new { cId = (string)product.Element("categoryId"), sId = (string)product.Element("supplierId") } into g
                select new { g.Key, g };
            foreach (var group in groups)
            {
                Console.WriteLine("Category id: {0}; supplier id: {1}:", group.Key.cId, group.Key.sId);
                foreach (var p in group.g)
                {
                    Console.WriteLine("\tProduct id: {0}", (string)p.Element("productId"));
                }
                Console.WriteLine();
            }
            Console.ReadLine();

------解决方案--------------------
C# code
var result = from x in list group x by x.key into groups select new { groups.key, groups.FirstOrDefault() };