如何在wp8中获取满足查询的记录

时间:2014-09-14 08:05:05

标签: c# linq windows-phone-8

我正在使用以下链接中的本地数据库。 http://www.c-sharpcorner.com/UploadFile/ae35ca/working-with-creating-a-local-database-in-wp7/

一切都运转良好,但我无法获取年龄= 15的项目

public IList<Employee> GetEmployeeList()
{
    IList<Employee> EmployeeList = null;
    using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString)
    {
        IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees select Emp;
        EmployeeList = EmpQuery.ToList();
    }
    return EmployeeList;
}
private void button4_Click(object sender, RoutedEventArgs e)
{
    IList<Employee> EmployeesList = this.GetEmployeeList();
    StringBuilder strBuilder = new StringBuilder();
    strBuilder.AppendLine("Employee Details");
    foreach (Employee emp in EmployeesList)
    {
        strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
    }
    MessageBox.Show(strBuilder.ToString());
}

以上代码获取所有记录。但我需要一个查询来获取只有15岁的项目。

2 个答案:

答案 0 :(得分:2)

这应该只是在LINQ语句中添加where子句的简单情况,如下所示:

var EmpQuery = from Emp in Empdb.Employees where emp.EmployeeAge == 15 select Emp;

答案 1 :(得分:1)

LINQ很懒。它只会在必要时执行实际的DB提取。

当您在.ToList上调用IQueryable时,您正在强制数据库枚举结果,从而从数据库中获取所有数据。

如果您希望数据库过滤结果而不是客户端 - 从IQueryable方法返回GetEmployeeList并过滤按钮上的那个:

public IQueryable<Employee> GetEmployeeList()
{
    // the database should be available on the class here, don't dispose it
    // or this won't work since it'll be disposed before you make a query
    return (from Emp in Empdb.Employees select Emp);
}
private void button4_Click(object sender, RoutedEventArgs e)
{
    var EmployeesList = this.GetEmployeeList();
    StringBuilder strBuilder = new StringBuilder();
    strBuilder.AppendLine("Employee Details");
    // now we can filter it
    foreach (Employee emp in EmployeesList.Where(e => e.EmployeeAge == 15)) 
    {
        strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
    } 
    // this could also be nicer with string.Join
    MessageBox.Show(strBuilder.ToString());
}