In the LINQ query below, I would like to add a property that gets the previous Department as well as the current Department.
The LINQ query below returns:
EffectiveDate EmployeeID Department
11/4/2012 10 0000
1/14/2013 10 9121
2/2/2016 10 9123
How can I show the previous Department next to current Department like this?
EffectiveDate EmployeeID Department PreviousDepartment
11/4/2012 10 0000 null
1/14/2013 10 9121 0000
2/2/2016 10 9123 9121
Here's the current query
var users = from s in userTable
where s.EmployeeID == "10"
group new {s} by new { s.EmployeeID, s.Department} into g
select new
{
EffectiveDate = g.Max(m => m.s.EffectiveDate),
EmployeeID = g.Key.EmployeeID,
Department = g.Key.Department
//PreviousDepartment = ???
};
One way to do it is to store the data in memory, and then modify it like this:
var users = from s in userTable
where s.EmployeeID == "10"
group new {s} by new { s.EmployeeID, s.Department} into g
select new MyClass
{
EffectiveDate = g.Max(m => m.s.EffectiveDate),
EmployeeID = g.Key.EmployeeID,
Department = g.Key.Department
PreviousDepartment = null
};
var result = users.ToList();
for(int i = 1; i < result.Count; i++)
{
result[i].PreviousDepartment = result[i-1].Department;
}
Please note that the code is generating new instances of MyClass instead of an anonymous type since anonymous type properties are read-only. Make sure that you create such class with the correct properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With