linq 如何选择一个新对象来包含其他对象的列表?

xuo3flqw  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(187)

我需要一些帮助来进行一个linq查询,该查询将选择一个Product对象列表。每个Product对象都包含一个ProductItem列表。我不知道如何创建Product. ProductItem列表。有人能帮我一把吗?这里是Product、ProductItem和我正在使用的xml结构的一个示例。
下面是我的研究方向的一个例子:

  1. XDocument xDocument = XDocument.Load("../Content/index.xml");
  2. return xDocument.Descendants("item")
  3. .Select(arg =>
  4. new Product
  5. {
  6. Name = arg.Parent.Attribute("name").Value,
  7. ProductItems = new ProductItem{//set properties for PI} // This is where Im stuck.
  8. })
  9. .ToList();
  10. }

我正在努力提高我的linq/lambda技能,所以如果你能给我一个使用lambda语法的例子,我将不胜感激!
非常感谢。

  1. public class Product
  2. {
  3. public string Name { get; set; }
  4. public IList<ProductItem> ProductItems { get; set; }
  5. }
  6. public class ProductItem
  7. {
  8. public string Hwid { get; set; }
  9. public string Href { get; set; }
  10. public string Localization { get; set; }
  11. public DateTime BuildDateTime { get; set; }
  12. public string IcpBuildVersion { get; set; }
  13. }

}

  1. <products>
  2. <product name="Product1">
  3. <item hwid="abk9184">
  4. <href>Product1/abk9184_en-us/abk9184.html</href>
  5. <localization>en-us</localization>
  6. <build.start>2011-06-08 22:02 PM</build.start>
  7. <build.icp>9.0.192.32</build.icp>
  8. </item>
  9. <item hwid="abk9185">
  10. <href>LearningModules/abk9185_en-us/abk9185.html</href>
  11. <localization>en-us</localization>
  12. <build.start>2011-06-08 22:03 PM</build.start>
  13. <build.icp>9.0.192.32</build.icp>
  14. </item>
  15. </product>
  16. <product name="Product2">
  17. <item hwid="aa6410">
  18. <href>Product2/aa6410_en-us/aa6410.html</href>
  19. <localization>en-us</localization>
  20. <build.start>2011-06-08 22:04 PM</build.start>
  21. <build.icp>9.0.192.32</build.icp>
  22. </item>
  23. <item hwid="tu6488">
  24. <href>Product2/tu6488_en-us/tu6488.html</href>
  25. <localization>en-us</localization>
  26. <build.start>2011-06-08 22:04 PM</build.start>
  27. <build.icp>9.0.192.32</build.icp>
  28. </item>
6mw9ycah

6mw9ycah1#

您应该遍历Product元素,而不是后代项。这样就更容易收集每个产品的项。

  1. var doc = XDocument.Load("../Content/index.xml");
  2. var products = doc.Elements("product")
  3. .Select(p => new Product
  4. {
  5. Name = (string)p.Attribute("name"),
  6. ProductItems = p.Elements("item")
  7. .Select(i => new ProductItem
  8. {
  9. //set properties for PI
  10. Hwid = (string)i.Attribute("hwid"),
  11. Href = (string)i.Element("href"),
  12. Localization = (string)i.Element("localization"),
  13. // etc.
  14. })
  15. .ToList(),
  16. })
  17. .ToList();
展开查看全部

相关问题