Home > Mobile >  C# linq select duplicate from an XElement tree
C# linq select duplicate from an XElement tree

Time:10-17

Here is my XElement tree

        XElement myShoppingList = new XElement("myShoppingList",
            new XElement("Pasadena", new XAttribute("Vendor", "Tesla"),
                new XElement("Car",
                    new XElement("model3",
                        new XElement("Black")))),
            new XElement("LasVegas", new XAttribute("Vendor", "Tesla"),
                new XElement("Car",
                    new XElement("modelY",
                        new XElement("White")))),
            new XElement("Pasadena", new XAttribute("Vendor", "Apple"),
                new XElement("Phone",
                    new XElement("model13",
                        new XElement("Black")))),
            new XElement("Pasadena", new XAttribute("Vendor", "Apple"),
                new XElement("Phone",
                    new XElement("model12",
                        new XElement("White")))));

I can't seems to get this working, first question - When searching for "Pasadena" I should be getting 3 repeats:

        var query = myShoppingList.Elements().AsEnumerable()
           .GroupBy(x => x.XPathSelectElement("Pasadena"))
          .Where(g => g.Count() > 1)
          .Select(y => new { Element = y.Key, Counter = y.Count() })
          .ToList();

When searching for Tesla in LasVegas I'm expecting 1 repeat

        var query = myShoppingList.Elements().AsEnumerable()
           .GroupBy(x => x.XPathSelectElement("Pasadena[@Name='Tesla']"))
          .Where(g => g.Count() > 1)
          .Select(y => new { Element = y.Key, Counter = y.Count() })
          .ToList();

And finally I want to search for "White" regardless of who makes the widget then display its maker. So I'm expecting 2 repeats:

       var query = myShoppingList.Elements().AsEnumerable()
           .GroupBy(x => x.XPathSelectElement("../../../White"))
          .Where(g => g.Count() > 1)
          .SelectMany(y => y})
          .ToList();

I'm not able get this working what am I doing wrong?

CodePudding user response:

I can't seems to get this working, first question - When searching for "Pasadena" I should be getting 3 repeats:

Is this what you're trying to achieve? :

var query = myShoppingList.XPathSelectElements("Pasadena")
    .GroupBy(x => x.Name)
    .Select(y => new { Element = y.Key, Counter = y.Count() });

When searching for Tesla in LasVegas I'm expecting 1 repeat

You could try it this way.

var query = myShoppingList.XPathSelectElements("Pasadena")
    .Where(x => x.Attributes().Any(x => x.Name == "Vendor" && x.Value == "Tesla"))
    .GroupBy(x => x.Name)
    .Select(y => new { Element = y.Key, Counter = y.Count() });

For this one i'm not sure if that's what you want to achieve

var query = myShoppingList.XPathSelectElements("//White")
    .GroupBy(x => x.Name)
    .Select(y => new { Element = y.Key, Counter = y.Count() });
  • Related