使用 join 子句可以根据特定的条件合并两个数据源,但之前要获得两个要连接的列表。
在一级方程式比 赛中,设有赛手冠军和制造商冠军。
赛手从GetChampions()方法中返回,制造商从GetConstructorChampions() 方法中返回。
现在要获得一个年份列表,列出每年的赛手和制造商冠军。
为此,先定义两个查询,用于查询赛手和制造商团队:
车手集合结构:
new Racer()
{
FirstName = "Michael",
LastName = "Schumacher",
Country = "Germany",
Starts = 250,
Wins = 91,
Years = new int[] { 1994, 1995, 2000, 2001, 2002, 2003, 2004 }, //冠军年
Cars = new string[] { "Benetton", "Ferrari" }
}
制造商集合结构:
new Team()
{
Name = "Ferrari",
Years = new int[] { 1961, 1964, 1975, 1976, 1977, 1979, 1982, 1983, 1999, 2000, 2001, 2002, 2003, 2004, 2007 } //冠军年
}
private static void Join() { var racers = from r in Formula1.GetChampions() from y in r.Years //获得车手中的年份集合 where y > 2003 //判断年份 select new { Year = y, Name = r.FirstName + " " + r.LastName }; //匿名对象定义,年份和名字是集合 var teams = from t in Formula1.GetContructorChampions() from y in t.Years where y > 2003 select new { Year = y, Name = t.Name }; //获得冠军年集合及制造商名字
有了这两个查询,再通过子句join t in teams on r.Year equals t.Year,根据赛手获得冠军的年份和制造商获得冠军的年份进行连接。
var racersAndTeams = from r in racers join t in teams on r.Year equals t.Year //和SQL的形式完全一样 select new { Year = r.Year, Racer = r.Name, Team = t.Name };
//select 子句定义了一个新的匿名类型,它包含Year、Racer 和Team 属性。 Console.WriteLine("Year Champion Constructor Title"); foreach (var item in racersAndTeams) { Console.WriteLine("{0}: {1,-20} {2}", item.Year, item.Racer, item.Team); } } 当然,也可以把它们合并为一个LINQ 查询,但这只是一种尝试:
private static void Join() { int year = 2003; var racersAndTeams = from r in from r1 in Formula1.GetChampions() from yr in r1.Years where yr > year select new { Year = yr, Name = r1.FirstName + " " + r1.LastName } join t in from t1 in Formula1.GetContructorChampions() from yt in t1.Years where yt > year select new { Year = yt, Name = t1.Name } on r.Year equals t.Year select new { Year = r.Year, Racer = r.Name, Team = t.Name }; Console.WriteLine("Year Champion Constructor Title"); foreach (var item in racersAndTeams) { Console.WriteLine("{0}: {1,-20} {2}", item.Year, item.Racer, item.Team); } }
结果如下:
冯瑞涛