Search code examples
c#asp.netlinq-to-xml

How to select column names using a lambda expression?


I am very new to lambda expressions.

I have this xml

<Booksshel>
   <BookN>
       <column>author</column>
       <column>Price</column>
       <column>Date</column>
   </BookN>
   <BookDetails id=1>
       <author>john</author>
       <price>50</price>
   </BookDetails>
   <BookDetails id=2>
       <author>kalam</author>
       <price>90</price>
   </BookDetails>
   <BookDetails id=3>
       <author>sachin</author>
       <price>70</price>
       <Date>12-08-2015</Date>
   </BookDetails>
</Booksshel>

In the above XML I have column names in a list 'author, price' that I need to select the particular BookDetails using a lambda expression.

foreach (var col in columnName)
{
    sl.AddRange(_doc.Descendants("BookDetails")
          .Where(p =>Id.Contains(p.Element("BookDetails").Value))
          .Select(p=> New { p.Element(col).Value }).ToList())
}

This is raising some strange issues. How can I get the details?


Solution

  • Since you mentioned you "need to select the particular BookDetails using a lambda expression" you can select the bookdetails for a specific book likfe this:

    var result = _doc.Descendants("BookDetails")
                     .Where(x => x.Attribute("id").Value == "1")
                     .Select(b => new { Author = b.Element("author").Value, Price = b.Element("price").Value });
    

    and you can loop through the results like this

    foreach (var book1 in result)
    {
        Console.WriteLine($"{book1.Author}\t\t{book1.Price}");
    }
    

    or since you are expceting one result you can get the item like this:

    var book2 = result.FirstOrDefault();
    if (book2 != null)
    {
        Console.WriteLine($"{book2.Author}\t\t{book2.Price}");
    }