如何重构多个类似的LINQ查询? [英] How to refactor multiple similar Linq queries?
本文介绍了如何重构多个类似的LINQ查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下两个LINQ查询我想重构:
Suppose I have the two following Linq queries I want to refactor:
var someValue1 = 0;
var someValue2= 0;
var query1 = db.TableAs.Where( a => a.TableBs.Count() > someValue1 )
.Take( 10 );
var query2 = db.TableAs.Where( a => a.TableBs.First().item1 == someValue2)
.Take( 10 );
请注意,只有当参数的变化。有什么办法可以把查询的方法内,作为参数传递的参数在哪里?
Note that only the Where parameter changes. There is any way to put the query inside a method and pass the Where parameter as an argument?
推荐答案
病程中出现。在其中,参数类型的只是一个简单的封闭 Func键< T,布尔>
(其中T是你的数据库的项目类型 - 我不知道出来的$的C $ C),你可以把它包装成一个(匿名)函数。
Of couse there is. The where parameter is just a simple closure of type Func<T, bool>
(where T is the type of your DB items - I don't know them out of your code) and you can wrap it into a (anonymous) function.
Func<Func<T, bool>, IEnumerable<T>> MakeQuery = (Func<T, bool> whereParam) => db.TableAs.Where(whereParam).Take(10);
使用像这样
var query1 = MakeQuery(a => a.TableBS.Count() > someValue1);
这篇关于如何重构多个类似的LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文