Skip to main content

Posts

Showing posts with the label Linq

Linq syntax for sql's not in and in

For In here how it goes var Userlist = new List<Int32> { 560, 561, 511, 611 }; var User= context.GetTable<Users>(); var q = (from p in User where Userlist.Contains(p.int_UserId) select p); For Not In here how it goes var Userlist = new List<Int32> { 560 }; var User= context.GetTable<Users>(); var q = (from p in User where !Userlist.Contains(p.int_UserId) select p);

Using Linq DefaultIfEmpty() extension method

By Using DefaultIfEmpty() extension method you can check the sequence for empty and return something for it and do some manipulation on it afterwards. For example var numbers = new int[] {1,2,3,4,5,6,7}; Console.WriteLine(numbers.DefaultIfEmpty().Sum()); If the sequence is empty it will return 0 otherwise it will sum and return that. By Default if you want to return some value other then 0 it will return that as well Console.WriteLine(numbers.DefaultIfEmpty(100).Sum()); In this case it will return 100 if the sequence is empty.

Left outer join in linq

Let's have a scenario in which there are two tables Teachers and Teacher_Courses .Teachers are assigned courses having teacherid in Teacher_Courses table as the foreign key. So to pick up all the Teacher's list with no of courses assigned regardless of having been assigned a course or not in linq you will be using left outer join as follows. using (TeacherContext context = new TeacherContext()) { var Teachers = context.Teachers; var TeacherCourse = context.TeacherCourses; var q = from c in Teachers join o in TeacherCourse on c.int_TeacherId equals o.int_TeacherId into j from Course in j.DefaultIfEmpty().GroupBy(m=>m.int_TeacherId) select new { Teachers = c.vcr_TeacherName, Courses = Course.Count() == 0 ? "(no Courses Assigned)" : Course.Where(m => m.int_TeacherId == c.i...