C# 使用LINQ向具有Dictionary属性的对象属性添加值

C# 使用LINQ向具有Dictionary属性的对象属性添加值,c#,linq,dictionary,C#,Linq,Dictionary,我有一个数据集,它返回stringPhone、mobile和skype中的一些联系信息。我创建了一个具有Dictionary属性的对象,可以将联系人信息放入一个键值对中。问题是,我正在使用Linq分配对象的值。希望有人能帮忙。这是我的密码: public class Student { public Student() { MotherContacts = new ContactDetail(); Fathe

我有一个数据集,它返回stringPhone、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
}
以下是我如何为学生对象赋值:

    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();
您以错误的方式使用对象初始值设定项语法。正确的用法是:


新学生{MotherContacts=value},其中value必须是ContactDetail。

这就解决了问题。这让我感到困惑,因为我正在为ContactDetails的属性项添加值。多谢各位much@KatrinaRivera如果有用,请标出答案并投票。