Skip to content

01 Expression连接以合并查询条件

Jinxin Chen edited this page Jan 2, 2020 · 1 revision

问题

假设有如下的方法,用来查询集合中的内容:

public List<Item> Get(string search, string source)

参数不多,我们可以这样写:

public List<Item> Get(string search, string source)
{
    if (null != search && null != source)
        return Items.Where( item => item.Description.Contains(search) && item.Source == source);
    else if (null != search)
        return xxx;
    else if (null != source)
        return xxx;
    else
        return xxx;
}

实际上这样的写法很糟糕了,如果参数更多呢?

此时可以考虑Expression来合并查询条件,最终的语法类似:

public List<Item> Get(string search, int page, string source)
{
    var pageSize = 100;
    var skip = (page - 1) * pageSize;
    Expression<Func<Item, bool>> filters = Item => true;
    if (null != source)
    {
        filters = filters.And<Item>(Item => Item.Source == source);
    }
    if (null != search)
    {
        filters = filters.And<Item>(Item => Item.Description.Contains(search));
    }

    return Items.Find(filters).Skip(skip).Limit(pageSize).ToList();
}

要实现这样的效果,还需要引入package:

dotnet add package Supperxin.Library

然后引入:

using Supperxin.Linq;

更多关于Expression,可以参考expression-tree

Clone this wiki locally