1

以下代码的等效 Linq to XML 是什么:

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;
    }
4

1 回答 1

7
    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>();
        }
    }
于 2009-03-16T21:46:05.253 回答