LINQ Joins in C#
أنواع الـ LINQ Joins في C#
في الدرس ده هنتعرف على أنواع الـ Joins في LINQ، واللي بتسمح لنا نربط بين أكثر من مجموعة بيانات زي ما بنعمل في SQL.
أنواع الـ Joins:
- Inner Join
- Left Outer Join
- Right Outer Join (محاكاة)
- Full Outer Join (محاكاة)
- Group Join
- Cross Join
تعريف الكائنات:
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int StandardID { get; set; }
}
public class Standard
{
public int StandardID { get; set; }
public string StandardName { get; set; }
}
البيانات:
List<Student> studentList = new List<Student>()
{
new Student() { StudentID = 1, StudentName = "John", StandardID = 1 },
new Student() { StudentID = 2, StudentName = "Moin", StandardID = 1 },
new Student() { StudentID = 3, StudentName = "Bill", StandardID = 2 },
new Student() { StudentID = 4, StudentName = "Ram", StandardID = 2 },
new Student() { StudentID = 5, StudentName = "Ron", StandardID = 3 }
};
List<Standard> standardList = new List<Standard>()
{
new Standard(){ StandardID = 1, StandardName = "Standard 1"},
new Standard(){ StandardID = 2, StandardName = "Standard 2"},
new Standard(){ StandardID = 3, StandardName = "Standard 3"},
new Standard(){ StandardID = 4, StandardName = "Standard 4"}
};
1. Inner Join:
var innerJoin = from s in studentList
join st in standardList
on s.StandardID equals st.StandardID
select new
{
StudentName = s.StudentName,
StandardName = st.StandardName
};
2. Group Join:
var groupJoin = from std in standardList
join s in studentList
on std.StandardID equals s.StandardID into studentGroup
select new
{
StandardName = std.StandardName,
Students = studentGroup
};
3. Left Outer Join:
var leftJoin = from std in standardList
join s in studentList
on std.StandardID equals s.StandardID into studentGroup
from student in studentGroup.DefaultIfEmpty()
select new
{
StandardName = std.StandardName,
StudentName = student?.StudentName ?? "No Student"
};
4. Cross Join:
var crossJoin = from std in standardList
from s in studentList
select new
{
StudentName = s.StudentName,
StandardName = std.StandardName
};
ملحوظات:
- Join بيستخدم مفتاح مشترك للربط.
- GroupJoin مفيد لما نحتاج نربط عنصر رئيسي مع مجموعة.
- Left Join و Full Join بيتعملوا يدويًا عن طريق
DefaultIfEmpty().
تعليقات
إرسال تعليق