内连接 Join
分别查询,查询数据再做连接
var racers = from r in Formula1.GetChampions()
from y in r.Years
select new
{
Year = y,
Name = r.FirstName + " " + r.LastName
};
var teams = from t in Formula1.GetConstructorChampions()
from y in t.Years
select new
{
Year = y,
Name = t.Name
};
var racersAndTeams = (from r in racers
join t in teams on r.Year equals t.Year
select new
{
r.Year,
Champion = r.Name,
Constructor = t.Name
}).Take(10);
合并在一起,直击内连接
var racersAndTeams = (from r in
from r1 in Formula1.GetChampions()
from yr in r1.Years
select new
{
Year = yr,
Name = r1.FirstName + " " + r1.LastName
}
join t in
from t1 in Formula1.GetConstructorChampions()
from yt in t1.Years
select new
{
Year = yt,
Name = t1.Name
}
on r.Year equals t.Year
orderby t.Year
select new
{
Year = r.Year,
Racer = r.Name,
Team = t.Name
}).Take(10);
使用方法连接
var racers = Formula1.GetChampions()
.SelectMany(r => r.Years, (r1, year) =>
new
{
Year = year,
Name = $"{r1.FirstName} {r1.LastName}"
});
var teams = Formula1.GetConstructorChampions()
.SelectMany(t => t.Years, (t, year) =>
new
{
Year = year,
Name = t.Name
});
var racersAndTeams = racers.Join(teams,
r => r.Year,
t => t.Year,
(r, t) =>
new
{
Year = r.Year,
Champion = r.Name,
Constructor = t.Name
}).OrderBy(item => item.Year).Take(10);
网友评论