LINQ to SQL的Where

2016-11-23  本文已影响13人  子武不是字母

与SQL命令中的Where作用相似,起到过滤作用。
一个员工安排到一辆车上,一辆车可以有很多员工,车牌号和员工号是一对多的关系。
员工类

public class Employee
{
       /// <summary>
       /// 车牌号
       /// </summary>
       public int CarNo { get; set; }

       /// <summary>
       /// 员工号
       /// </summary>
       public string EmployeeNo { get; set; }

       /// <summary>
       /// 描述
       /// </summary>
       public string Description { get; set; }

       /// <summary>
       /// 年龄
       /// </summary>
       public int Age { get; set; }
}

获取员工数据方法

public static List<Employee> GetList()
{
        return new List<Employee>()
        {
                 new Employee(){ CarNo=1,EmployeeNo="NO-1",Description ="广州分公司",Age=21},
                 new Employee(){ CarNo=2,EmployeeNo="NO-2",Description ="惠州分公司",Age=30},
                 new Employee(){ CarNo=3,EmployeeNo="NO-3",Description ="东莞分公司",Age=27},
                 new Employee(){ CarNo=4,EmployeeNo="NO-4",Description ="广州分公司",Age=28},
                 new Employee(){ CarNo=3,EmployeeNo="NO-4",Description ="东莞分公司",Age=52},
                 new Employee(){ CarNo=1,EmployeeNo="NO-5",Description ="深圳分公司",Age=18},
                 new Employee(){ CarNo=1,EmployeeNo="NO-6",Description ="中山分公司",Age=21},
                 new Employee(){ CarNo=2,EmployeeNo="NO-7",Description ="广州分公司",Age=31},
                 new Employee(){ CarNo=5,EmployeeNo="NO-8",Description ="佛山分公司",Age=19},
                 new Employee(){ CarNo=6,EmployeeNo="NO-9",Description ="深圳分公司",Age=20}
        };
}

获取年龄大于30岁的所有员工信息

var employeeList = Employee.GetList();
var list = employeeList.Where(x => x.Age > 30);
StringBuilder sb = new StringBuilder();
foreach (var item in list)
{
      sb.AppendFormat("员工号{0},描述:{1},年龄:{2}<br/> ", item.EmployeeNo, item.Description, item.Age);
}

输出结果:

员工号NO-4,描述:东莞分公司,年龄:52
员工号NO-7,描述:广州分公司,年龄:31

获取年龄大于20岁并且坐1号车的所有员工信息

var employeeList = Employee.GetList();
var list = employeeList.Where(x => x.Age > 20 && x.CarNo == 1);
StringBuilder sb = new StringBuilder();
foreach (var item in list)
{
      sb.AppendFormat("员工号{0},描述:{1},年龄:{2}<br/> ", item.EmployeeNo, item.Description, item.Age);
}

或者

var employeeList = Employee.GetList();
var list = employeeList.Where(x => x.Age > 20).Where(x => x.CarNo == 1);
StringBuilder sb = new StringBuilder();
foreach (var item in list)
{
      sb.AppendFormat("员工号{0},描述:{1},年龄:{2}<br/> ", item.EmployeeNo, item.Description, item.Age);
}

输出结果:

员工号NO-1,描述:广州分公司,年龄:21
员工号NO-6,描述:中山分公司,年龄:21
上一篇下一篇

猜你喜欢

热点阅读