2014-03-25 75 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