-
Notifications
You must be signed in to change notification settings - Fork 56
/
Joins.cs
76 lines (68 loc) · 3.05 KB
/
Joins.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Linq;
namespace StandardOperators
{
public static class Joins
{
private static readonly CourseChoice[] choices =
{
new CourseChoice { StudentId = 1, Category = "MAT", Number = 101 },
new CourseChoice { StudentId = 1, Category = "MAT", Number = 102 },
new CourseChoice { StudentId = 1, Category = "MAT", Number = 207 },
new CourseChoice { StudentId = 2, Category = "MAT", Number = 101 },
new CourseChoice { StudentId = 2, Category = "BIO", Number = 201 },
};
public static void QueryWithJoin()
{
CourseChoice[] choices =
{
new CourseChoice { StudentId = 1, Category = "MAT", Number = 101 },
new CourseChoice { StudentId = 1, Category = "MAT", Number = 102 },
new CourseChoice { StudentId = 1, Category = "MAT", Number = 207 },
new CourseChoice { StudentId = 2, Category = "MAT", Number = 101 },
new CourseChoice { StudentId = 2, Category = "BIO", Number = 201 },
};
var studentsAndCourses = from choice in choices
join course in Course.Catalog
on new { choice.Category, choice.Number }
equals new { course.Category, course.Number }
select new { choice.StudentId, Course = course };
foreach (var item in studentsAndCourses)
{
Console.WriteLine(
$"Student {item.StudentId} will attend {item.Course.Title}");
}
}
public static void JoinOperator()
{
var studentsAndCourses = choices.Join(
Course.Catalog,
choice => new { choice.Category, choice.Number },
course => new { course.Category, course.Number },
(choice, course) => new { choice.StudentId, Course = course });
}
public static void GroupedJoin()
{
var studentsAndCourses =
from choice in choices
join course in Course.Catalog
on new { choice.Category, choice.Number }
equals new { course.Category, course.Number }
into courses
select new { choice.StudentId, Courses = courses };
foreach (var item in studentsAndCourses)
{
Console.WriteLine($"Student {item.StudentId} will attend " +
string.Join(",", item.Courses.Select(course => course.Title)));
}
}
public static void GroupedJoinOperator()
{
var studentsAndCourses = choices.GroupJoin(
Course.Catalog,
choice => new { choice.Category, choice.Number },
course => new { course.Category, course.Number },
(choice, courses) => new { choice.StudentId, Courses = courses });
}
}
}