如何将类添加到字典中的嵌套类

本文关键字:嵌套 字典 添加 | 更新日期: 2023-09-27 18:31:01

这是我Dictionary

的结构
public class Company
{
    public string ComID { get; set; }
    public string ComName { get; set; }
    public List<Dep> Dep { get; set; }
}
public class Dep
{
    public string DepID { get; set; }
    public string DepName { get; set; }
    public string isDepAt { get; set; }
    public List<User> User { get; set; }
}
public class User
{
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string UserTitle { get; set; }
    public string UserExt { get; set; }
    public string UserIsAt { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    Dictionary<int, Company> dic = new Dictionary<int, Company>();
    DataTable data=new DataTable();
    //get data ...
    //Creat User
    //Creat Dep and add User to class
    //Creat Company and add Dep to class
    //Add Company to Dictionary 'dic'
}

数据绑定后,如何在Dictionary中添加新User

我使用这种方式:

User _user = new User()
    {
        UserID = "123",
        UserName = "John cena",
        UserTitle = "Champian",
        UserExt = "7777",
        UserIsAt = "Yes"
    };
dic.Where(x => x.Value.Dep.Select(y => y.DepID == "abcDep").FirstOrDefault()).FirstOrDefault().Value.Dep.Where(z => z.DepID == "abcDep").FirstOrDefault().User.Add(_user);

有更好的方法吗?

如何将类添加到字典中的嵌套类

var curDepId = "abcDep";
 var curUser=new User()
          {
              UserID = "123",
              UserName = "John cena",
              UserTitle = "Champian",
              UserExt = "7777",
              UserIsAt = "Yes"
           };
foreach (var d in dic)
{ 
    var curCompany=d.Value;
    if (curCompany == null || curCompany.Dep==null) continue;
    var depObj = curCompany.Dep.Where(c => c.DepID == curDepId).FirstOrDefault();
    if (depObj != null)
    { 
        if(depObj.User==null)
        {
         depObj.User=new List<User>();
        }
        depObj.User.Add(curUser);
        break;
    }
}