Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current and previous value

Tags:

c#

linq

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 = ???
            };
like image 682
jaykzoo Avatar asked May 24 '26 04:05

jaykzoo


1 Answers

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.

like image 167
Yacoub Massad Avatar answered May 26 '26 18:05

Yacoub Massad