2016年7月21日木曜日

LINQ Where句動的 AsQueryable()を使う。と可読性が増す

int? categoryID = null;
string categoryName = string.Empty;
string description = string.Empty;

// nullチェックとORでくっつけてやる
from c in ctx.Categories
where (categoryID == null || c.CategoryID == categoryID)
&& (string.IsNullOrEmpty(categoryName) || c.CategoryName == categoryName)
&& (string.IsNullOrEmpty(description) || c.Description == description)
select c;
↓でWhere句を動的に書ける。
var q = ctx.Categories.AsQueryable();
if (categoryID != null)
{
    q = q.Where(c => c.CategoryID == categoryID);
}
if (!string.IsNullOrEmpty(categoryName))
{
    q = q.Where(c => c.CategoryName == categoryName);
}

0 件のコメント:

コメントを投稿