简体   繁体   English

使用LINQ向带有Dictionary属性的对象属性添加值

[英]Adding values using LINQ to an object property with a Dictionary property

I have a dataset which returns a couple of contact information in string(Phone, mobile, skype) . 我有一个数据集,该数据集以string(Phone, mobile, skype)返回了几个联系信息。 I created an object with a Dictionary property where i can put the contact information in a key value pair. 我创建了一个具有Dictionary属性的对象,可以在其中将联系信息放入键值对中。 The problem is, I am assigning the values of the object using Linq. 问题是,我正在使用Linq分配对象的值。 Hope somebody can help. 希望有人能帮忙。 Here is my code: 这是我的代码:

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
}

Here's how I assign value to the Student object: 这是我为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();

The compiler says that the MotherContacts is not recognized in the context. 编译器说在上下文中无法识别MotherContacts What should I do? 我该怎么办?

I think your code should look like: 我认为您的代码应如下所示:

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();

You are using the object initializer syntax in a wrong way. 您以错误的方式使用了对象初始化器语法。 The correct use is: 正确的用法是:

new Student{MotherContacts = value} where value must be a ContactDetail . new Student{MotherContacts = value} ,其中value必须是ContactDetail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM