我设置了一个 Entity Framework 类来从 SQL 数据库中读取一个表,但我不太清楚如何传递 LINQ 表达式以仅过滤某些对象。我知道有一种方法可以构建表达式树并在类中动态执行此操作,但我似乎无法找到执行此操作的最佳方法。
如有任何提示,我们将不胜感激。
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
class MyObjectCollection<T> where T : class
{
private List<T> myInternalCollection = new List<T>();
MyObjectCollection()
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>())
{
// Enumerate the data, do whatever with it...
myInternalCollection.Add(row);
}
}
}
MyObjectCollection(var MyLinqExpression)
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>().Where.MyLinqExpression()
{
// Enumerate the data, do whatever with it...
myInternalCollection.Add(row);
}
}
}
}
// Works fine:
MyObjectCollection<Customer> allCustomers = new MyObjectCollection<Customer>();
// Would like something like this:
MyObjectCollection<Customer> customersP = new MyObjectCollection<Customer>(c => c.StartsWith("P"));
最佳答案
Linq Where 方法采用参数 Func<T, bool>
其中 T 是您要应用 Where 方法的 dbSet 对象类型。
为了让您的代码正常工作,您可以这样做:
public MyObjectCollection(Func<T, bool> MyLinqExpression)
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>().Where(MyLinqExpression))
{
// Enumerate the data, do whatever with it...
myInternalCollection.Add(row);
}
}
}
更新:
此外,要使用通用集合实现您正在寻找的功能,而不是封装私有(private) List 对象,您可以从 List 继承,如下所示。所以,如果你想要 MyObjectCollection
要像列表一样运行,您可以像我在下面展示的那样做。
因此,使用上面的代码,您可以更改为:
public class MyObjectCollection<T> : List<T> where T : class
{
public MyObjectCollection()
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>())
{
// Enumerate the data, do whatever with it...
this.Add(row);
}
}
}
public MyObjectCollection(Func<T, bool> MyLinqExpression)
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>().Where(MyLinqExpression))
{
// Enumerate the data, do whatever with it...
this.Add(row);
}
}
}
}
关于c# - 将 LINQ 表达式作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885587/