Search code examples
c#sql-serverlinqlinq-to-sqlsql-to-linq-conversion

Convert sql code to linq (Inner join Query)


Could somebody help me please to convert this sql code to linq .

SQL query

select distinct  coursecode
from UnitSet_Unit  
where UnitCode  in ('FDFFSACA' ,'FDFFSCFSAA', 'FDFOPTHCP3A ')
and CourseCode in (Select  distinct  coursecode
                  from Trainee_course
                  where TraineeID =10000088 )

Where UnitCode in IN clause come dynamic and in the form of array . and the course code in the second part is also have variable count


Solution

  • Off the top of my head, assuming we have the following inputs (and you are working in C#):

    var unitCodes = new List<string> { "FDFFSACA" ,"FDFFSCFSAA", "FDFOPTHCP3A" };
    var traineeID = 10000088;
    

    This should work:

    var result = (from us in db.UnitSet_Unit
                  where unitCodes.Contains(us.UnitCode)
                  && us.CourseCode == (from tc in db.Trainee_course
                                       where tc.TraineeID == traineeID
                                       select tc.CourseCode).Distinct().SingleOrDefault()
                  select us.CourseCode).Distinct();