LINQ subquery with AND operator displays no results

19,883

I'd simplify it with an extension method to do the tricky lookup:

(updated 12/02/09 to exclude empty elements)

static string CategoryValue(this XElement element, string type)
{
    var category = element.Elements("category").FirstOrDefault(
        c => (string)c.Attribute("type") == type
            && !string.IsNullOrEmpty(c.Value)); // UPDATE HERE
    return category == null ? null : category.Value;
}

static void Main()
{
    XDocument doc = XDocument.Parse(xml);
    var qry = from item in doc.Descendants("item")
              where item.CategoryValue("Channel") == "Automotive"
              && item.CategoryValue("Type") == "Cars"
              select item;
    foreach (var node in qry)
    {
        Console.WriteLine(node.Element("guid").Value);
    }
}
Share:
19,883
Ejazkhan
Author by

Ejazkhan

Updated on September 03, 2022

Comments

  • Ejazkhan
    Ejazkhan almost 2 years

    Me again... I have an XML File that contains different categories which I would like to query for different attributes.

            <item>      
                <title>Industries</title>      
                <category type="Channel">Automotive</category>      
                <category type="Type">Cars</category>      
                <category type="Token">Article</category>      
                <category type="SpecialToken">News</category>      
                <guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid>
            </item>
    

    IN SQL I would write something like.

    select * from articles where channel = 'Automative' AND type = 'Cars' etc. etc.
    

    How can I achieve this with linq? I tried the following query but it returns null. If I combine the two attributes with the "OR" || operator I would get the results, but with all double results if an item matches both criteria.

    var articleList = (from item in doc.Descendants("item")
    
                             from _category in item.Elements("category")
                             where _category.Value == valueCboChannel && _category.Attribute("domain").Value == "Channel"
                             && (_category.Value == valueCboSubChannel && _category.Attribute("domain").Value == "SubChannel")
    
                             select new
                             {
    
                                 Title = item.Element("title").Value,
                                 Guid= item.Element("guid").Value,
                                 description = item.Element("description").Value,
                                 link = item.Element("link").Value
                             }).ToList();
    
                ListView1.DataSource = articleList;
                ListView1.DataBind();