简体   繁体   English

LINQ和可选参数

[英]LINQ and optional parameters

I'm designing a web service to be consumed by an MVC app (pretty simple stuff), but I need a single method in the web service that takes up to four optional parameters (ie catId, brandId, lowestPrice and highestPrice). 我正在设计一个由MVC应用程序使用的Web服务(非常简单的东西),但我需要在Web服务中使用一个方法,该方法最多需要四个可选参数(即catId,brandId,lowestPrice和highestPrice)。

How do I write the Linq query so that it essentially executes 如何编写Linq查询以使其基本上执行

databaseObject.Products.Where(p=> (p.Category == ANY if catId==null, else catId))

I hope that makes sense. 我希望这是有道理的。

The parameters of the method could accept null values and the Where restriction could be evaluated for each not null parameter: 该方法的参数可以接受空值,并且可以为每个非null参数计算Where限制:

IQueryable<Product> q = databaseObject.Products;

if (catId != null)
{
    q = q.Where(p => p.Category == catId);
}
if (brandId != null)
{
    q = q.Where(p => p.Brand == brandId);
}
// etc. the other parameters

var result = q.ToList();

If this is Linq To SQL: 如果这是Linq To SQL:

databaseObject.Products.Where(p=> (catId == null || p.Category == catId) );

Linq To SQL, efficiently writes the SQL sent to backend without a where clause if CatId is null. Linq To SQL,如果CatId为null,则有效地将发送到后端的SQL写入而不使用where子句。 You can have multiple of these constructs, and only those with a nonNull value is included in the where construct. 您可以拥有多个这样的构造,只有那些具有nonNull值的构造才包含在where构造中。

databaseObject.Products.Where(p=> ((catId==null) ||  (p.Category == catId)))

对于其他3个可选参数,您可以将它们输入,在一个linq语句中进行整个搜索。

Something along the lines of the following should do the trick: 下面的内容应该可以解决问题:

IEnumerable<Product> GetProducts(int? categoryId)
{
    var result = databaseObject.Products.Where(product => ProductCategoryPredicate(product, categoryId)
}

/// <summary>
/// Returns true if the passed in categoryId is NULL
/// OR if it's not null, if the passed in categoryId matches that
/// of the passed in product
///
/// This method will get called once for each product returned from 
/// databaseObject.Products</summary>
bool ProductCategoryPredicate(Product product, int? categoryId)
{
    if (categoryId.HasValue)
    {
        return product.Category == categoryId.Value;
    }
    else
    {
        return true;
    }
}

This could/can be simplified into a single line LINQ statement (see below) but I've written it long-hand above for clarity: 这可以/可以简化为单行LINQ语句(见下文),但为了清楚起见,我在上面写了它:

IEnumerable<Product> GetProducts(int? categoryId)
{
    var result = databaseObject.Products.Where(product => !categoryId.HasValue || product.Category == categoryId.Value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM