2016-01-20 61 views
-1

这是我Dictionary如何将类添加到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); 

有更好的办法来做到这一点?

+0

不知道你在寻找什么样的帮助。很明显,你期望的项目有时不会被发现(因为你正在使用'FirstOrDefault()'),但是如图所示的其他手形代码(大概简化/组合在一行中作为后期样本)并不处理项目不存在的情况。请确保提供包含'null'处理的完整代码,以便有人可以为您的实际代码提供合理的建议。 –

+0

如果内部集合有频繁更新,为什么不能使用字典instread?比如'Dictionary ' –

回答

0
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; 
    } 
}