// #8 Group join ships by companies public void GroupJoinShips() { XElement xRoot = XDocument.Load(_path).Root; var ships = xRoot.Element("companies").Elements("company") .GroupJoin(xRoot.Element("links").Elements("link"), c => c.Attribute("id").Value, link => link.Element("companyid").Value, (c, links) => new { Company = XmlToObject.CreateCompany(c), Ships = links.Join(xRoot.Element("ships").Elements("ship"), l => l.Element("shipid").Value, s => s.Attribute("id").Value, (l, s) => XmlToObject.CreateShip(s)) }); foreach (var pair in ships) { Console.WriteLine($"{pair.Company}:"); foreach (var ship in pair.Ships) { Console.WriteLine(ship); } Console.WriteLine(); } }
// #1 public void OrderedShips() { XElement xRoot = XDocument.Load(_path).Root; var ships = xRoot.Element("ships").Elements("ship") .OrderBy(s => s.Element("name").Value) .Select(s => XmlToObject.CreateShip(s)); Console.WriteLine("Ordered ships:\n"); foreach (var ship in ships) { Console.WriteLine(ship); } Console.WriteLine(); }
// #6 public void ShipsWhile() { XElement xRoot = XDocument.Load(_path).Root; var ships = xRoot.Element("ships").Elements("ship") .TakeWhile(s => s.Element("name").Value != "Admiral Lunin") .Select(s => XmlToObject.CreateShip(s)); Console.WriteLine("Ships before \"Admiral Lunin\":"); foreach (var ship in ships) { Console.WriteLine(ship); } Console.WriteLine(); }
// #9 Intersection public void IntersectShips() { XElement xRoot = XDocument.Load(_path).Root; var ships = (from s in xRoot.Element("ships").Elements("ship") where s.Element("name").Value.StartsWith("A") || s.Element("name").Value.StartsWith("V") select s) .Intersect(from s in xRoot.Element("ships").Elements("ship") where s.Element("name").Value.StartsWith("L") || s.Element("name").Value.StartsWith("A") select s) .Select(s => XmlToObject.CreateShip(s)); Console.WriteLine("Ships which names starts with \'A\':"); foreach (var ship in ships) { Console.WriteLine(ship); } Console.WriteLine(); }
// #7 Group companies by waters id public void GroupCompanies() { XElement xRoot = XDocument.Load(_path).Root; var companies = from company in xRoot.Element("companies").Elements("company") group company by company.Element("waterid").Value into g select new { Key = g.Key, Companies = g.Select(c => XmlToObject.CreateCompany(c)) }; Console.WriteLine("Grouped companies by waters id:\n"); foreach (var pair in companies) { Console.WriteLine(pair.Key); foreach (var c in pair.Companies) { Console.WriteLine(c); } Console.WriteLine(); } Console.WriteLine(); }