tags:

views:

149

answers:

1

What is the equivalent Linq to XML for the following code:

public List<listing> GetList()
    {
        List<listing> listings = new List<listing>();

        if(File.Exists(this.XmlFilePath))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(this.XmlFilePath);
            DataTable dt = ds.Tables["listing"];

            for(int row = 0; row < dt.Rows.Count; row++)
            {
                listing listing = new listing();

                listing.A = dt.Rows[row]["A"].ToString();
                listing.B = dt.Rows[row]["B"].ToString();
                listing.C = dt.Rows[row]["C"].ToString();
                listing.D= dt.Rows[row]["D"].ToString();
                listing.E = dt.Rows[row]["E"].ToString();

                listings.Add(listing);
            }
        }
        return listings;
    }
+7  A: 
    public List<Listing> GetList()
    {
        if (File.Exists(this.xmlFilePath))
        {
            XDocument doc = XDocument.Load(this.xmlFilePath);

            var listings = from row in doc.Root.Elements("listing")
                           select new Listing
                           {
                               A = (string)row.Element("A"),
                               B = (string)row.Element("B"),
                               C = (string)row.Element("C"),
                               D = (string)row.Element("D"),
                               E = (string)row.Element("E")
                           };

            return listings.ToList();
        }
        else
        {
            return new List<Listing>();
        }
    }
Thomas Danecker
Hi, Thanks. Someone asked above in the comment if I really need LINQ to XML or if I can just use LINQ. I am not really sure what he meant, because I would think if I am reading from an XML file, I would use LINQ to XML.
Xaisoft