Question : LINQ Query not yielding expected results

Hello Everyone.

So I have the following XML:


       
       

       
       
       
       
   
      
       

       
       
       
       
   



with the following query:


String number = "22222";
      
      XDocument Facility = XDocument.Load(facility.xml");
      var query =
      from
      cFa in Facility.Descendants("cofacility")
      where
      cFa.Element("facility").Element("company").Attribute("no").Value == number
      select cFa.Elements("facility").Elements("contact");



So what I am trying to get all the contacts in all the facilities that are part of a specific company number.  So for example, if I ask for company "number" = 12345, I should get the following:

           
         
         
         

and when I use number =  "55555" I should only get

           
           

However, my query does not give me a result when I use "55555" or "22222".  What I am doing wrong?  and how can I just the the values out instead of the entire XElement?

Thanks for you help.
 
 

Answer : LINQ Query not yielding expected results

Hi Kozela;

There are two ways to get the value of the attribute name. Both of these are in the code snippet below.

Fernando
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
// Get the Attribute name from within the query
XDocument Facility = XDocument.Load("facility.xml");
var query = from cFa in Facility.Descendants("cofacility").Elements("facility")
            from cNo in cFa.Elements("company")
            where cNo.Attribute("no").Value == number
            select cFa.Elements("contact").Attributes("name");

foreach (var q in query)
{
    foreach(string contact in q)
    {
        Console.WriteLine(contact.ToString());
    }
}


// Get the Attribute name after the query when you enumerate the query itself
XDocument Facility = XDocument.Load("facility.xml");
var query = from cFa in Facility.Descendants("cofacility").Elements("facility")
            from cNo in cFa.Elements("company")
            where cNo.Attribute("no").Value == number
            select cFa.Elements("contact");

foreach (var q in query)
{
    foreach (XElement contact in q)
    {
        Console.WriteLine(contact.Attribute("name").Value);
    }
}
Random Solutions  
 
programming4us programming4us