2011-12-27 1 views
1

Email에 대한 별도의 필드가있는 클래스가 있습니다. 그럼 난리플렉션을 사용하여 이름과 카운터 값이 같은 여러 속성 값을 설정하는 방법은 무엇입니까?

Email9 나는 단일 사용자의 접촉 또는 최대 9 연락처에있을 수 없다이

<user Email="[email protected]"> 
    <Contact Name="test1" Email="[email protected]"/> 
    <Contact Name="test2" Email="[email protected]"/> 
</user> 

같은 XML의 형태로 값을받을 Email1, Email2 ... 같은 필드가 있습니다. linq을 사용하여이 값을 내 속성에 어떻게 할당 할 수 있습니까?

public class User 
{ 
    public List<Contact> Contacts { get; set; } 
    public string Email { get; set; } 
} 

public class Contact 
{ 
    public string Name { get; set; } 
    public string Email { get; set; } 
} 

그런 다음 클래스를 채우는 데 사용되는 LINQ 쿼리 수 있습니다 : 당신이 당신의 클래스 User에 추가 엔티티 Contact이 있어야합니다, 그래서 당신은 다음과 같이 설명 된대로 각 사용자가 List<Contact>을 가질 수 있습니다 더 나은 디자인을 위해

답변

0

다음과 같이 :

XElement xmlDoc = XElement.Load(@"..\Users.xml"); 
var users = from x in xmlDoc.Elements() 
      select new User 
      {     
       Email = (string) x.Attribute("Email"), 
       Contacts = new List<Contact>(
          from c in x.Elements() 
          select new Contact 
          { 
           Name = (string) c.Attribute("Name"), 
           Email = (string) c.Attribute("Email") 
          } 
       ) 
      }; 
관련 문제