创建一个Players类
如下:
public class Players
{
public string Name { get; set; }
public string Team { get; set; }
public int Position { get; set; }
}
详细代码如下:
static void Main(string[] args)
{
// 创建数据源
var players = new List()
{
new Players(){ Name=“麻辣香锅”,Position=5,Team=“RNG”},
new Players(){ Name=“UZI”,Position=3,Team=“RNG”},
new Players(){ Name=“厂长”,Position=5,Team=“EDG”},
new Players(){ Name=“TheShy”,Position=1,Team=“IG”},
new Players(){ Name=“Rookie”,Position=2,Team=“IG”},
new Players(){ Name=“林炜翔”,Position=3,Team=“FPX”},
};
var teams = new List<Teams>()
{
new Teams(){ ID=1,Team="RNG"},
new Teams(){ ID=2,Team="IG"},
new Teams(){ ID=3,Team="EDG"},
new Teams(){ ID=4,Team="FPX"},
};
// 创建联合查询,查看选手的信息及其俱乐部ID
var query = from p in players // 找数据源
join t in teams // 找第二个数据源
on p.Team equals t.Team // 连接条件
orderby p.Team.Length
select new // 投影
{
aa = p.Team + "队的编码是:" + t.ID,
};
//方法语法查询
var query1 = players.Join(teams, p => p.Team, t => t.Team, (p, t) => new
{
aa = p.Name,
bb = p.Team,
cc = t.ID,
}).OrderBy(s=>s.aa.Length);
Console.WriteLine("---------查看选手的信息及其俱乐部ID--------");
// 执行查询
foreach (var item in query1)
{
Console.WriteLine(item.aa + item.bb + item.cc);
}
//创建查询 找到IG的选手
var query2 = from p in players
where p.Team.Contains("G")
select p;
//方法查询
var query3 = players.Where(p => p.Team.Contains("G"));
Console.WriteLine("---------创建查询 找到IG的选手--------");
foreach (var item in query3)
{
Console.WriteLine(item.Name);
}
// 按战队分组查询选手,查看各战队人数
var query4 = from p in players // 数据源
group p by p.Team // 分组
into pp // 新建数据源
select new
{ // 投影操作
pp.Key,
Nums = pp.Count()
};
//方法查询
var query5 = players.GroupBy(a => a.Team).Select(pp => new
{
pp.Key,
Nums=pp.Count()
});
Console.WriteLine("---------按战队分组查询选手,查看各战队人数--------");
// 执行查询
foreach (var item in query4)
{
Console.WriteLine(item.Key+item.Nums);
}
}