Home > Enterprise >  How To Filter First in Last Out record In LINQ
How To Filter First in Last Out record In LINQ

Time:03-15

I have Data In List It is the employee's entry and exit information.

Datetime                 User_id              UserName              Tna
--------------------------------------------------------------------------------
2022-03-15 08:30:23      01                   John                  null
2022-03-15 09:43:40      01                   John                  null
2022-03-15 10:16:52      01                   John                  null
2022-03-15 13:45:23      01                   John                  null
2022-03-15 15:38:23      01                   John                  null
2022-03-15 17:36:23      01                   John                  null
2022-03-15 08:31:23      02                   Eva                   null
2022-03-15 10:16:52      02                   Eva                   null
2022-03-15 13:45:23      02                   Eva                   null
2022-03-15 15:38:23      02                   Eva                   null
2022-03-15 17:30:23      02                   Eva                   null

Information in List retrieved from API.

I would like to know how to filter the items in the list. First check-in and last check-out by filtering by time , How to get output like this using LINQ?

Datetime                 User_id              UserName              Tna
--------------------------------------------------------------------------------
2022-03-15 08:30:23      01                   John                  IN
2022-03-15 17:36:23      01                   John                  OUT
2022-03-15 08:31:23      02                   Eva                   IN
2022-03-15 17:30:23      02                   Eva                   OUT

CodePudding user response:

You may want group by person, then select first and last of each group.

Assumption
Every person has at least one in and out entry.

pseudocode

   var result = lst.GroupBy(x => x.User_id)
                   .Select(g => g.OrderBy(x => x.Datetime))
                   .Select(g => new[] { g.First() }.Concat(new[] { g.Last() }));
  • Related