今天写了一段linq,感觉还是很生疏,贴出来记录一下!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Employee
{
public int ID { set; get;}
public string Name { set; get; }
public int Age { set; get; }
public int RoleId { set; get; }
}
class Role
{
public int RoleId { set; get; }
public string RoleName { set; get; }
}
class Program
{
static void Main(string[] args)
{
List<Employee> listEmployee = new List<Employee>()
{
new Employee{ ID = 1, Name = "Employee1", Age = 20,RoleId = 1},
new Employee{ ID = 2, Name = "Employee2", Age = 21,RoleId = 2},
new Employee{ ID = 3, Name = "Employee3", Age = 22,RoleId = 2},
new Employee{ ID = 4, Name = "Employee4", Age = 23,RoleId = 2},
new Employee{ ID = 5, Name = "Employee5", Age = 24,RoleId = 2}
};
List<Role> listRole = new List<Role>()
{
new Role{ RoleId = 1, RoleName = "Admin"},
new Role{ RoleId = 2, RoleName = "Guest"},
new Role{ RoleId = 3, RoleName = "None"}
};
var q = from e in listEmployee
where e.Age == 20
select new Employee { ID = 6, Age = e.Age, Name = "EmployeeNew" };
foreach (var item in q)
{
Console.WriteLine("id:" + item.ID + ",name:" + item.Name + ",age:" + item.Age + ".");
}
//inner join
var p = from r in listRole
join e in listEmployee on r.RoleId equals e.RoleId where r.RoleId == 1
select new { e.Name, e.RoleId };
foreach (var item in p)
{
Console.WriteLine("RoleId:" + item.RoleId + ",name:" + item.Name + ".");
}
//group join
var query = from r in listRole
join e in listEmployee on r.RoleId equals e.RoleId into ss where r.RoleId == 1
select new { r.RoleId,ss };
foreach (var item in query)
{
Console.Write("RoleId:" + item.RoleId + ",");
foreach (var s in item.ss)
{
Console.WriteLine("name:" + s.Name);
}
}
//left join
var query2 = from r in listRole
join e in listEmployee on r.RoleId equals e.RoleId into ss where r.RoleId == 1
from s in ss.DefaultIfEmpty(new Employee { ID = 0, Name = string.Empty, Age = 0, RoleId = 0 })
select new { r, ss };
foreach (var item in query2)
{
Console.Write("RoleId:" + item.r.RoleId + ",");
foreach (var s in item.ss)
{
Console.WriteLine("name:" + s.Name);
}
}
Console.ReadKey();
}
}
}