簡體   English   中英

LINQ和可選參數

[英]LINQ and optional parameters

我正在設計一個由MVC應用程序使用的Web服務(非常簡單的東西),但我需要在Web服務中使用一個方法,該方法最多需要四個可選參數(即catId,brandId,lowestPrice和highestPrice)。

如何編寫Linq查詢以使其基本上執行

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

我希望這是有道理的。

該方法的參數可以接受空值,並且可以為每個非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();

如果這是Linq To SQL:

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

Linq To SQL,如果CatId為null,則有效地將發送到后端的SQL寫入而不使用where子句。 您可以擁有多個這樣的構造,只有那些具有nonNull值的構造才包含在where構造中。

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

對於其他3個可選參數,您可以將它們輸入,在一個linq語句中進行整個搜索。

下面的內容應該可以解決問題:

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;
    }
}

這可以/可以簡化為單行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