LINQ 常用方法
学习LINQ的一些常用方法
初始化数据
- Employee.cs
class Employee
{
public long Id { get; set; } //ID
public string Name { get; set; }//姓名
public int Age { get; set; } //年龄
public bool Gender { get; set; } //性别
public int Salary { get; set; } //月薪
public override string ToString()
{
return $"ID={Id},Name={Name},Age={Age},Gender={Gender},Salary={Salary}";
}
}
- 初始化
class Program
{
public static List<Employee> EmpList;
/// <summary>
/// 初始化数据
/// </summary>
public static void initEmployee()
{
Random random = new Random();
EmpList = new List<Employee>();
for (int i = 1; i <= 30; i++)
{
int _age = random.Next(1,47);
bool _gender = false;
if (i % 2 == 0) _gender= true;
int _salary = random.Next(1,11);
EmpList.Add(new Employee { Id = i, Name = "刘波" + i + "号", Age = _age, Gender = _gender, Salary = _salary * 1000});
}
}
}
常用方法
where()
返回集合, 从数据源中筛选数据;
IEnumerable<Employee> items = EmpList.Where(e => e.Gender == true);
count()
返回总条数(int), 满足条件的总条数
Console.WriteLine(EmpList.Count(e => e.Salary > 6000 && e.Age > 32));
Any()
是否有满足条件的数据(bool)
Console.WriteLine(EmpList.Any());
Single()
返回对象,从数据源中查找符合条件的一组数据;(若没有该数据则抛出异常)
Employee employee = EmpList.Single(a => a.Id == 1);
SingleOrDefault()
返回对象,从数据源中查找符合条件的一组数据;(若没有该数据则返回默认值)
Employee employeeDefault = EmpList.SingleOrDefault(a => a.Id == 100);
First()
返回对象,查找符合条件数据源中的 第一组 数据;(若没有该数据则抛出异常)
Employee emp = EmpList.First(a => a.Salary>1000);
FirstOrDefault()
返回对象,查找符合条件数据源中的 第一组 数据;(若没有该数据则返回默认值)
Employee emp = EmpList.FirstOrDefault(a => a.Salary>10000);
排序
OrderBy()
返回 IEnumerable< > 数组,根据某项 正序排列
IEnumerable<Employee> iEmp = EmpList.OrderBy(a => a.Age);
foreach (Employee item in iEmp)
{
Console.WriteLine(item.ToString());
}
OrderByDescending()
返回 IEnumerable< > 数组,根据某项 倒序排列
IEnumerable<Employee> iEmp = EmpList.OrderByDescending(a => a.Age);
foreach (Employee item in iEmp)
{
Console.WriteLine(item.ToString());
}
Guid.NewGuid()
随机排序
IEnumerable<Employee> iEmp = EmpList.OrderByDescending(a => Guid.NewGuid());
foreach (Employee item in iEmp)
{
Console.WriteLine(item.ToString());
}
ThenBy()
排序后 有重复的再根据一列排序(正序)ThenByDescending()
倒序
IEnumerable<Employee> iEmp = EmpList.OrderByDescending(a => a.Age).ThenBy(a => a.Salary);
Skip()
跳过n条数据Take()
获取n条数据
聚合函数
-
Max()
-
Min()
-
Sum()
-
Count()
-
Average()
平均 -
select()
投影映射 -
需要注意类型
IEnumerable<string> iEmp = EmpList.Select(e => e.Id+","+e.Name);
foreach (string item in iEmp)
{
Console.WriteLine(item.ToString());
}
- 创建对象 映射
var itmes = EmpList.Select(e => new { e.Age, e.Name, XB= e.Gender ? "男" : "女"});
foreach (var item in itmes)
{
Console.WriteLine("==");
Console.WriteLine(item);
}