Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exists query with LINQ

Tags:

c#

.net

linq

I'd like to get with LINQ an employee list, these employees must have in the TypeOfWorks list the typeofWork passed (Id) in argument

  public class Employee 
    {   
        public virtual IList<EmployeeTypeOfWork> TypeOfWorks { get; set; }
    }

    public class EmployeeTypeOfWork 
    {
        public virtual Guid Id { get; set; }
        public virtual Employee Employee { get; set; }
        public virtual TypeOfWork TypeOfWork { get; set; }
    }

    public class TypeOfWork 
    {
        public virtual Guid Id { get; set; }
    }

    public IList<Employee> ListWithTypeOfWork(IList<Employee> Employees, 
Guid typeOfWorkId)
    {     
        ?????       
    }

I tried this but I missed something I think

        var res = from p in Employees
        where (from pp in p.TypeOfWorks 
    where pp.TypeOfWork.Id == guid select pp.Id).Contains(p.Id)
        select p;
like image 362
Kris-I Avatar asked Jan 23 '23 08:01

Kris-I


2 Answers

Try the following

var res = Employees
  .Where(x => x.TypeOfWorks.Any(w => w.Id == guid))
like image 103
JaredPar Avatar answered Jan 25 '23 21:01

JaredPar


public IEnumerable<Employee> ListWithTypeOfWork(IList<Employee> Employees, Guid typeOfWorkId)
{     
    return from emp in Employees
        where emp.TypeOfWorks.Any(x => x != null && x.Id == typeOfWorkId)
        select emp;          
}
like image 24
Ben Lesh Avatar answered Jan 25 '23 22:01

Ben Lesh