2014-03-25 79 views
1

我有一個數據集,它返回string(Phone, mobile, skype)中的幾個聯繫信息。我創建了一個Dictionary屬性的對象,我可以將聯繫信息放入一個鍵值對中。問題是,我正在使用Linq分配對象的值。希望有人能幫助。這裏是我的代碼:使用LINQ將值添加到具有Dictionary屬性的對象屬性中

public class Student 
    { 
     public Student() 
     { 
      MotherContacts = new ContactDetail(); 
      FatherContacts = new ContactDetail(); 
     } 
     public ContactDetail MotherContacts { get; set; } 
     public ContactDetail FatherContacts { get; set; } 
    } 

public class ContactDetail 
{ 
    public ContactDetail() 
    { 
     Items = new Dictionary<ContactDetailType, string>(); 
    } 
    public IDictionary<ContactDetailType, string> Items { get; set; } 

    public void Add(ContactDetailType type, string value) 
    { 
     if(!string.IsNullOrEmpty(value)) 
     { 
      Items.Add(type, value); 
     } 
    } 
} 

public enum ContactDetailType 
{ 
    PHONE, 
    MOBILE 
} 

下面是我給你的價值Student對象:

var result = ds.Tables[0].AsEnumerable(); 
    var insuranceCard = result.Select(row => new Student() 
     { 
      MotherContacts.Items.Add(ContactDetailType.PHONE, row.Field<string>("MotherPhone"), 
      MotherContacts.Items.Add(ContactDetailType.MOBILE, row.Field<string>("MotherMobile") 
     }).FirstOrDefault(); 

編譯器說,MotherContacts不是在上下文的認可。我該怎麼辦?

回答

0

我覺得你的代碼應該是這樣的:

var insuranceCard = result.Select(row => 
{ 
    var s = new Student(); 
    s.MotherContacts.Items.Add(ContactDetailType.PHONE, row.Field<string>("MotherPhone"); 
    s.MotherContacts.Items.Add(ContactDetailType.MOBILE, row.Field<string>("MotherMobile"); 
    return s; 
}).FirstOrDefault(); 

您正在使用的對象初始化語法錯誤​​的方式。正確的用法是:

new Student{MotherContacts = value}其中值必須是ContactDetail

+0

這樣做。它讓我感到困惑,因爲我將值添加到ContactDetails屬性的Items中。非常感謝 –

+0

@KatrinaRivera如果有用,請標記答案和投票。 – agarwaen