Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How To Filter First in Last Out record In LINQ

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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() }));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading