Selection with LINQ

I have an example XML file that looks like this:

<Books>
   <Category Genre="Fiction" BookName="book_name" BookPrice="book_price_in_$" />
   <Category Genre="Fiction" BookName="book_name" BookPrice="book_price_in_$" />
   <Category Genre="NonFiction" BookName="book_name" BookPrice="book_price_in_$" />
   <Category Genre="Children" BookName="book_name" BookPrice="book_price_in_$" />
</Books>  

I need to collect all the names of books and books and move on to another method. Right now, I get all the book and book names separately in two different ones List<string>using the following command:

List<string>BookNameList = root.Elements("Category").Select(x => (string)x.Attribute("BookName")).ToList();
List<string>BookPriceList = root.Elements("Category").Select(x => (string)x.Attribute("BookPrice")).ToList();

I create a text file and send it back to the calling function (these results must be executed in a text file, the text file has two fields bookname and bookprice).

The following code is used to write to a text file:

for(int i = 0; i < BookNameList.Count; i++)
{
   //write BookNameList[i] to file
   // Write BookPriceList[i] to file
}

- . - . , , foreach (, , ). LINQ ( )? foreach.

# .

,

[Edit]: , , .

+3
4

:

var books = root.Elements("Category").Select(x => new {
    Name = (string)x.Attribute("BookName"), 
    Price = (string)x.Attribute("BookPrice")
}).ToList();

:

foreach (var book in books)
{
    // do something with
    // book.Name
    // book.Price
}
+10

, .

.

:

public class Book
{
   public Book(string name, string price)
   {
      Name = name;
      Price = price;
   }

   public string Name { get; set; }
   public string Price { get; set; } // could be decimal if we want a proper type.
}

XML- , :

var books = from category in root.Elements("Category")
            select new Book((string) x.Attribute("BookName"), (string) x.Attribute("BookPrice"));

, XmlReader , . , , , .

:

using (var outputFile = OpenOutput())
using (XmlReader xml = OpenInput())
{
   try
   {
       while (xml.ReadToFollowing("Category"))
       { 
           if (xml.IsStartElement())
           {
               string name = xml.GetAttribute("BookName");
              string price = xml.GetAttribute("BookPrice");

              outputFile.WriteLine(string.Format("{0} {1}", name, price));
          }
      }
   }
   catch (XmlException xe)
   {
        // Parse error encountered. Would be possible to recover by checking
        // ReadState and continue, this would obviously require some 
        // restructuring of the code.
        // Catching parse errors is recommended because they could contain
        // sensitive information about the host environment that we don't
        // want to bubble up.
        throw new XmlException("Uh-oh");
   }       
}

, XML, XmlReader NameTable .

+2

foreach.

var namesAndPrices = from category in root.Elements("Category")
                     select new
                     {
                        Name = category.Attribute("BookName").Value,
                        Price = category.Attribute("BookPrice").Value
                     };

foreach (var nameAndPrice in namesAndPrices)
{
    // TODO: Output to disk
}
+1

Jeff, , KeyValuePair a - :

var namesAndPrices = from category in root.Elements("Category")
                     select new KeyValuePair<string, string>(
                        Name = category.Attribute("BookName").Value,
                        Price = category.Attribute("BookPrice").Value
                     );

// looping that happens in another function
// Key = Name
// Value = Price
foreach (var nameAndPrice in namesAndPrices)
{
    // TODO: Output to disk
}
+1

Source: https://habr.com/ru/post/1751630/


All Articles