這裏使用時讓我的數據:如何避免重新創建對象使用LINQ
private List<Department> Data
{
get
{
return new List<Department>
{
new Department{
Id = 1,
Name = "Tech",
Employees = new List<Employee>{
new Employee{Name = "x", Id = 1 },
new Employee{ Name = "y", Id = 2}
}
},
new Department{
Id = 2,
Name = "Sales",
Employees = new List<Employee>{
new Employee{Name = "a", Id = 3},
new Employee {Name = "b", Id = 4}
}
}
};
}
}
,在這裏我得到的所有員工與他們相關部門的列表:
List<Employee> employees = (from department in Departments
let d = department
from e in d.Employees
select new Employee{
Id = e.Id,
Name = e.Name
Department = d
}).ToList();
是什麼在困擾我是我必須重新創建我的Employee對象才能將相應的部門附加到它。有沒有一種方法可以寫我的LINQ語句,我不需要重新創建員工?
有可能是一個更好的方式來短語這個question--可以隨意讓我知道是有。
編輯 我走這條路的原因是,我存儲我的數據通過序列化我的部門:
[
{
"Id":1,
"Name":"Sales",
"Employees":[{"Id":2,"Name":"x"},{"Id":1,"Name":"y"}]
},
{
"Id":2,
"Name":"Tech",
"Employees":[{"Id":3,"Name":"d"},{"Id":4,"Name":"f"}]
}
]
您可以標記兩個類序列化和序列化列表中,將保持該部門爲了與員工。 – terrybozzio