2014-09-07 2 views
1

LINQ를 사용하여 개체를 만들고이 개체 내에서 목록을 초기화하는 방법은 무엇입니까? (또한, 불변 개체를 만들려고합니다.) XML 웹 서비스에 액세스하고 있습니다.LINQ to Objects - 초기화 목록

예를 들어, 여러 속성이있는 클래스가 있습니다. 그러나, 나는 또한 수업 중에 개인 목록을 가지고있다.

public class MyClass 
{ 
    public string SomeProperty { get; private set; } 
    public string AnotherProperty { get; private set; } 

    internal List<Result> ResultSet1 { get; set; } 
    internal List<Result> ResultSet2 { get; set; } 

    public IEnumerable<Result> GetResultSet1() 
    { 
     return ResultSet1; 
    } 

    //Constructor here to set the private properties eg: this.SomeProperty = someProperty; 

    //etc. 
} 

그리고는 내가 Result.cs 있습니다

public class Result 
{ 
    public string YetAnotherProperty { get; private set; } 
    //etc. 
} 

지금까지 내가 XML을 읽고 "MyClass에"개체를 만든 다음이 생성자를 통해 속성의 설정 LINQ를 사용하는 수입니다. 그러나, 나는하는 하나 방법을 모르는 :

  • 는 LINQ 쿼리 내에서 List<Result> 초기화를

이있는 LINQ 쿼리 내에서 목록에 Result의 속성을 변경하는 방법

  • LINQ는 지금까지 있습니다

    //Use the contents of XML nodes/elements as the arguments for the constructor: 
    var query = from i in document.Descendants("response") 
              select new MyClass 
              (
               (string)i.Element("some").Element("property"), 
               (string)i.Element("another").Element("property") 
              ) 
    

    내 질문 : 내가 LI에 대해 충분히 모른다 NQ를 만들거나 LINQ를 사용하여 개체를 만들면 내가 만들려고하는 개체 내에서 목록을 초기화하는 방법을 알 수 있습니다. 어떻게해야합니까? LINQ에서 ResultSet1에 항목을 어떻게 추가합니까? 이 꽤 불쾌한 얻을 수 있지만

    var query = from i in document.Descendants("response") 
             select new MyClass 
             (
              (string)i.Element("some").Element("property"), 
              (string)i.Element("another").Element("property") 
             ) 
             { 
              ResultSet1 = new List<Result> 
                { 
                 new Result { YetAnotherProperty = ... }, 
                 new Result { ... }    
                }, 
              ResultSet 2 = ... 
             }; 
    

    을하고 힘든 길을 디버깅 할 수 있도록 수 :

  • 답변

    1

    은 당신의 생성자를 호출 한 후 객체 이니셜을 추가합니다. 노드를 가져 와서 파싱 한 생성자는 어떻습니까?

    3

    속성에 액세스 할 수 있다고 가정하면 일반 개체 이니셜 라이저 구문을 통해 속성을 설정하기 만하면됩니다. new 호출 후에 중괄호 쌍을 추가하고 속성을 설정하면됩니다.

    var query = 
        from response in document.Descendants("response") 
        // for readability 
        let someProperty = (string)response.Element("some").Element("property") 
        let anotherProperty = (string)response.Element("another").Element("property") 
        select new MyClass(someProperty, anotherProperty) 
        { 
         ResultSet1 = response.Elements("someSet") 
          .Select(ss => new Result 
          { 
           YetAnotherProperty = (string)ss.Element("another") 
                   .Element("property") 
          }) 
          .ToList() 
         ResultSet2 = /* etc. */, 
        }; 
    
    +0

    나는 더 많은 것을 읽을 수있다. – Jonesopolis

    관련 문제