具有多个未知条件的Where子句 [英] Where clause with multiple unknown conditions

查看:98
本文介绍了具有多个未知条件的Where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为公司开发人员管理系统.这些字段可能会有所不同,并且会随时间变化,所以我为每个字段都提供了这样的界面:

I am currently developing a Staff management system for my company. The fields may vary and change time to time, so I have an interface for each field like this:

public interface IStaffInfoField
{

    // ...

    IQueryable<Staff> Filter(IQueryable<Staff> pList, string pAdditionalData);

    // ...

}

对于每个字段,我都实现Filter方法,例如使用Name:

For each field, I implement the Filter method, for example with Name:

class NameStaffInfoField : BaseStaffInfoField
{

    // ...

    public override IQueryable<Staff> Filter(IQueryable<Staff> pList, string pAdditionalData)
    {
        return pList.Where(q => q.Name.Contains(pAdditionalData));
    }

    // ...

}

现在用户想要在多个条件下进行搜索,这很容易,我只需遍历列表并调用Filter.但是,他们也希望使用OR条件(例如,具有名称A,或名称B,AND部门名称C,或年龄30的员工). 注意:用户是最终用户,他们通过组合框和文本框输入搜索查询.

Now the users want to search with multiple conditions, it's easy, I just iterate through the list and call Filter. However, they also want a OR condition (say, staff which have name A, OR name B, AND Department Name C, OR Age 30). Note: Users are end-users and they input the search queries through comboboxes and textboxes.

我可以通过某种方式修改我的模式或lambda表达式来实现吗?因为在整个开发过程中,我不会保存原始列表以将其合并为OR条件.我认为如果保存表达式并将其并为OR条件,将会很慢.

Can I modify my pattern or the lambda expression somehow to achieve that? Because throughout the progress, I don't save the original list to Union it for OR condition. I think it will be slow if I save the expression and Union it for OR condition.

我现在唯一想到的解决方案是在需要原始SQL WHERE语句的接口中添加一个方法.但是我的整个程序还没有使用纯SQL查询,现在使用它不好吗?

The only solution I can think of now is to add a method to interface that require raw SQL WHERE statement. But my entire program hasn't used pure SQL query yet, is it bad to use it now?

推荐答案

您可以下载Albahari的 LINQKit .它包含一个 PredicateBuilder ,除其他有用的功能外,它还允许您使用OR将LINQ表达式连接起来.以动态的方式.

You can download Albahari's LINQKit. It contains a PredicateBuilder that allows you, among other useful things, to concatenate LINQ expressions with OR in a dynamic way.

var predicate = PredicateBuilder.False<Staff>();
predicate = predicate.Or(s => s.Name.Contains(data));
predicate = predicate.Or(s => s.Age > 30);
return dataContext.Staff.Where(predicate);

您还可以下载源代码并查看其实现方式.

You can also download the source code and see how it is implemented.

这篇关于具有多个未知条件的Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆