The problem:
I have a xml variable Xdocument in C# like this:

I want to do a “group by” all the same records:


the two solutions:
one is using linq to do a groupby directly to the xml variable:

  XDocument output = new XDocument(
           new XElement(xmlvar.Root.Name,
                        xmlvar.Root.Elements("f")
                        .GroupBy(a => a.Element("v0").Value)
                        .Select(g => new XElement("f",
                         g.ElementAt(0).Elements().Where(e => e.Name != "Balance")
                                    ))));

another aproach is to use a datatable and the “magic” function /*distinct*/:

table= BasicHelper.ToDataTable(xmlvar);
DataTable distinctTable = table.DefaultView.ToTable( /*distinct*/ true);

public static DataTable ToDataTable(this XDocument element)
        {
            if (element != null)
            {
                DataSet ds = new DataSet();
                string rawXml = element.ToString();
                ds.ReadXml(new StringReader(rawXml));
                return ds.Tables[0];
            }
            else
                return null;
        }
Facebooktwittergoogle_plusredditpinterestlinkedinmail