简体   繁体   中英

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 .

Have try making it

.Distinct().ToList();

You can refer hereLINQ: Distinct values

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();

使用 GroupBy 区分

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

Have you try:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM