Get distinct values from list

    public List<MAS_EMPLOYEE_TRANSFER> GetEmployeeTransferListForHR(TimecardDataContext TimecardDC)
    {
        List<MAS_EMPLOYEE_TRANSFER> objEmployeeTransferList = null;
        try
        {
            objEmployeeTransferList = new List<MAS_EMPLOYEE_TRANSFER>();
            objEmployeeTransferList = TimecardDC.MAS_EMPLOYEE_TRANSFER.Where(
                employee =>
                    employee.HR_ADMIN_IND=="Y").ToList();                
        }
        finally
        {
        }
        return objEmployeeTransferList;
    }

It shows all list of values where hr admin indicator=yes. But I have to get hr admin=yes and distinct(empid) from the table MAS_EMPLOYEE_TRANSFER. How to get distinct empId from the the objEmployeeTransferList.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Have try making it

.Distinct().ToList();

You can refer here LINQ: Distinct values

Method 2

List<int> ids = objEmployeeTransferList
                   .Select(e => e.empId)
                   .Distinct()
                   .ToList();

Also you can make this on server side without creating in-memory employee list with all admin records:

List<int> ids = TimecardDC.MAS_EMPLOYEE_TRANSFER
                   .Where(e => e.HR_ADMIN_IND == "Y")
                   .Select(e => e.empId)
                   .Distinct()
                   .ToList();

Method 3

Get Distinct using GroupBy

objEmployeeTransferList.GroupBy(x => x.empId).Select(g => g.First()).ToList();

Method 4

Have you try:

objEmployeeTransferList = TimecardDC.MAS_EMPLOYEE_TRANSFER.Where(
   employee => employee.HR_ADMIN_IND=="Y").Distinct().ToList();

Method 5

There is a distinct method in linq which should do the trick.

http://msdn.microsoft.com/en-gb/library/bb348436.aspx


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x