[英]Adding values using LINQ to an object property with a Dictionary property
我有一個數據集,該數據集以string(Phone, mobile, skype)
返回了幾個聯系信息。 我創建了一個具有Dictionary屬性的對象,可以在其中將聯系信息放入鍵值對中。 問題是,我正在使用Linq分配對象的值。 希望有人能幫忙。 這是我的代碼:
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
。 我該怎么辦?
我認為您的代碼應如下所示:
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}
,其中value必須是ContactDetail
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.