Linq to SQL-如何使用条件进行选择并返回IQueryable

本文关键字:选择 行选 返回 IQueryable 条件 to SQL- 何使用 Linq | 更新日期: 2023-09-27 17:58:27

我找不到如何实现以下场景的答案(我不知道该找什么方法)。我使用C#.NET FW4.5Linq进行SQL和设计模式库。

如果我想选择所有设备,请使用以下代码:

/// <summary>
/// Get all Devices
/// </summary>
/// <returns></returns>
public IQueryable<Device> GetDevices()
{
    return myDataContext.Devices;
}

如果我想通过ID选择设备,请使用以下代码:

/// <summary>
/// Get Device by ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Device GetDevice(int id)
{
    return myDataContext.Devices.SingleOrDefault(
        d => d.intDeviceId == id);
}

但是我该如何实现以下情况呢?

选择所有设备,其中有一些条件(并返回IQueryable<Device>

Linq to SQL-如何使用条件进行选择并返回IQueryable

尝试:

return myDataContext.Devices.Where(
        d => yourConditions).AsQueryable();

您可以像一样使用它

public IQueryable<Device> GetDeviceUsingPredicate(Expression<Func<Device,bool>> predicate)
{
    return myDataContext.Devices.Where(predicate).AsQueryable();
}

与仿制药一起使用:

public IQueryable<T> GetDeviceUsingPredicate(Expression<Func<T,bool>> predicate)
{
    return myDataContext.GetTable<T>().Where(predicate).AsQueryable();
}