我有一个方法:
- public static void GetObjects()
- {
- using(MyContext context = new MyContext())
- {
- var objects = context.Bars.Where(b => b.Prop1 != null)
- .Select(b => new MyObject{Prop = b.Prop1,Name = b.Name})
- .ToList();
- foreach(var object in objects)
- {
- // do something with the object
- }
- }
- }
我重构了这个方法,使之更通用,以便我可以传入一个Func,以便我可以指定where语句和Bars表中什么属性分配给MyObject.Prop,如下所示:
- public static void GetObjectsV2(Func<Bar,bool> whereFunc,Func<Bar,string> selectPropFunc)
- {
- using(MyContext context = new MyContext())
- {
- var objects = context.Bars.Where(whereFunc)
- .Select(b => new MyObject{Prop = selectPropFunc(b),Name = b.Name})
- .ToList();
- foreach(var object in objects)
- {
- // do something with the object
- }
- }
- }
GetObjectsV2似乎比GetObjects慢得多.是否有任何理由会影响性能,如果是这样,有什么办法可以保持功能的灵活性吗?
解决方法
运行速度较慢的原因是因为您正在传入一个Func< Bar,bool>这将强制上下文重新启动所有条,然后在返回的结果集上运行Func.使这种运行更好的方法是在表达式< Func< Bar,bool>>
将所有这些结合在一起将导致以下内容:
- public static void GetObjectsV2(Expression<Func<Bar,bool>> whereFunc,Expression<Func<Bar,string>> selectPropFunc)
- {
- using(MyContext context = new MyContext())
- {
- var objects = context.Bars.Where(whereFunc)
- .Select(selectPropFunc)
- .ToList();
- foreach(var object in objects)
- {
- // do something with the object
- }
- }
- }