2011-06-11 2 views
3

Product 객체 목록을 선택할 linq 쿼리를 만드는 데 도움이 필요합니다. 각 제품 개체에는 ProductItem 목록이 포함되어 있습니다. 어떻게해야하는지 잘 모르는 부분은 Product.ProductItems 목록을 만드는 방법입니다. 누군가 나에게 손을 댈 수 있습니까? 다음은 Product, ProductItem 및 재생중인 xml 구조의 예입니다.Linq - 다른 개체의 목록을 포함 할 새 개체를 선택하려면 어떻게해야합니까?

XDocument xDocument = XDocument.Load("../Content/index.xml"); 
      return xDocument.Descendants("item") 
       .Select(arg => 
         new Product 
         { 
          Name = arg.Parent.Attribute("name").Value, 
          ProductItems = new ProductItem{//set properties for PI} // This is where Im stuck. 


         }) 
       .ToList(); 
     } 

난 당신이 내가 감사하겠습니다 람다 구문을 사용하는 저와 예를 들어 줄 수 있다면 그래서 내 LINQ/람다 기술을 선명하게하려고 : 여기

내가이 함께가는 방향의 예입니다 그것!

감사합니다.

public class Product 
{ 
    public string Name { get; set; } 
    public IList<ProductItem> ProductItems { get; set; } 

} 

public class ProductItem 
{ 
    public string Hwid { get; set; } 
    public string Href { get; set; } 
    public string Localization { get; set; } 
    public DateTime BuildDateTime { get; set; } 
    public string IcpBuildVersion { get; set; } 
} 

}

<products> 
<product name="Product1"> 
    <item hwid="abk9184"> 
    <href>Product1/abk9184_en-us/abk9184.html</href> 
    <localization>en-us</localization> 
    <build.start>2011-06-08 22:02 PM</build.start> 
    <build.icp>9.0.192.32</build.icp> 
    </item> 
    <item hwid="abk9185"> 
    <href>LearningModules/abk9185_en-us/abk9185.html</href> 
    <localization>en-us</localization> 
    <build.start>2011-06-08 22:03 PM</build.start> 
    <build.icp>9.0.192.32</build.icp> 
    </item> 
</product> 
<product name="Product2"> 
    <item hwid="aa6410"> 
    <href>Product2/aa6410_en-us/aa6410.html</href> 
    <localization>en-us</localization> 
    <build.start>2011-06-08 22:04 PM</build.start> 
    <build.icp>9.0.192.32</build.icp> 
    </item> 
    <item hwid="tu6488"> 
    <href>Product2/tu6488_en-us/tu6488.html</href> 
    <localization>en-us</localization> 
    <build.start>2011-06-08 22:04 PM</build.start> 
    <build.icp>9.0.192.32</build.icp> 
    </item> 

답변

12

당신은 Product 후손이 아닌 항목을 통과해야한다. 그렇게하면 Product 요소를 읽을 수 있습니다. 그런 다음 관련 항목을 가져 오는 것이 더 쉽습니다.

var doc = XDocument.Load("../Content/index.xml"); 
var products = doc.Elements("product") 
    .Select(p => 
     new Product 
     { 
      Name = (string)p.Attribute("name"), 
      ProductItems = p.Elements("item") 
       .Select(i => 
        new ProductItem 
        { 
         //set properties for PI 
         Hwid = (string)i.Attribute("hwid"), 
         Href = (string)i.Element("href"), 
         Localization = (string)i.Element("localization"), 
         // etc. 
        }) 
       .ToList() 
     }) 
    .ToList(); 
+0

의미가 있습니다. 나는 당신이 두 번째 선택을 어떻게하고 있는지 보았다. 좋아 보인다. 고맙습니다! – Nick

관련 문제