Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NOT IN Condition in Linq

I have a simple scenario.I want to list out all the employees except the logged in user.

Similar SQL Condition is

select * from employee where id not in(_loggedUserId) 

How can I acheive the above using LINQ.I have tried the following query but not getting the desired list

int _loggedUserId = Convert.ToInt32(Session["LoggedUserId"]);

List<int> _empIds = _cmn.GetEmployeeCenterWise(_loggedUserId)                              
                        .Select(e => e.Id)
                        .Except(_loggedUserId) 
                        .ToList();
like image 383
ksg Avatar asked Dec 19 '22 21:12

ksg


2 Answers

Except expects argument of type IEnumerable<T>, not T, so it should be something like

_empIds = _cmn.GetEmployeeCenterWise(_loggedUserId)                              
                           .Select(e => e.Id)
                           .Except(new[] {_loggedUserId}) 
                           .ToList();

Also note, this is really redundant in the case when exclusion list contains only one item and can be replaces with something like .Where(x => x != _loggedUserId)

like image 163
Andrey Korneyev Avatar answered Jan 10 '23 20:01

Andrey Korneyev


Why not use a very simple Where condition?

_empIds = _cmn.GetEmployeeCenterWise(_loggedUserId).Where(e=>e.Id != _loggedUserId).ToList();
like image 26
Kosala W Avatar answered Jan 10 '23 22:01

Kosala W