读书人

关于Linq的一个小疑点

发布时间: 2012-02-23 22:01:34 作者: rapoo

关于Linq的一个小问题
代码如下:

void GetProduct(string strWhere)
{
var northwind = new NorthwindDataContext(); //NorthwindDataContext 是上下文,为dbml文件
var IsWhere = !string.IsNullOrEmpty(strWhere);
var products = (from p in northwind.product
select p).[color=#FF0000]where(IsWhere ? strWhere: "productid > 0 ");[/color]
....................
}

大家注意[color=#FF0000]红色[/color]的位置。由于where中的参数应该是个表达式

而由于系统中需要,这里必须是上述的情况,请问如何转换?

谢谢大家了!

[解决办法]

C# code
// 我猜你是想让where条件自己用字符串拼出来// 那样不行// 曾经有多少新手想让C#有JavaScript的Eval()那样的功能object  GetProduct(delegate(product) dl){        var   northwind   =   new   NorthwindDataContext();        IEnumable<product> products;        if(dl!=null)          products   =   northwind.product.where(p=>p.productid>0);        else          products   =   northwind.product.where(dl);}
[解决办法]
简单的例子:

void GetProduct <T>(Func<T,bool> predicate)
{
var northwind = new NorthwindDataContext(); //NorthwindDataContext 是上下文,为dbml文件
var products = (from p in northwind.product
select p).Where(predicate);
}

调用:
GetProduct<Product>(p=>p.ProductID > 0);

读书人网 >.NET

热点推荐