简体   繁体   English

如何跳过具有多个条件的“Where”子句中的条件?

[英]How to skip conditions in "Where" clause with multiple conditions?

I"m working on a WinfForms/C# software for automotive key management that's has a SQL query thats searchs in the table like that:我正在开发一个用于汽车密钥管理的 WinfForms/C# 软件,它有一个 SQL 查询,在表格中搜索如下:

DataAdapter = SetAdapter($"SELECT * FROM keylist WHERE MANUFACTOR LIKE @manufactor AND KEYTYPE LIKE @type AND SERVICETYPE LIKE @service AND USER_ID = @_user");

So in the begginig I used to use the query directly in the search function but as the project grew, it ended up leaving it without performance, because the query was called directly on the remote server.所以在开始时,我曾经直接在搜索 function 中使用查询,但是随着项目的增长,它最终导致它没有性能,因为查询是直接在远程服务器上调用的。 So I decided to move everything to a list in C # and do the search with lambdas functions.所以我决定将所有内容移到 C # 的列表中,并使用 lambdas 函数进行搜索。

This is the function with lambda expression:这是 function 和 lambda 表达式:

 public List<Key> SearchFilter(string manufactor, string type, string service)
 {
     return _keys.Where(key =>  key.Manufactor == manufactor
                                 && key.Type == type
                                 && key.ServiceType == service).ToList();

 }

The problem is: In the SQL syntax, when you leave one or more fields, it automatically ignores and checks for the other, but when I use Where <> in the LINQ for example, it ends up returning null or items that do not satisfy conditions and returning other objects.问题是:在 SQL 语法中,当您留下一个或多个字段时,它会自动忽略并检查另一个字段,但是当我在 LINQ 中使用 Where <> 时,例如,它最终返回 Z37A6259CC660C1DAFFAE299A7 或 8 个不满足的项目条件并返回其他对象。

When I leave one or two of the parameters null, it returns no value.当我留下一个或两个参数 null 时,它没有返回任何值。 By the way, if I use ||顺便说一句,如果我使用 || instead of && it returns undesirable values.而不是 && 它返回不需要的值。

Is there a way to check if the condition is null and skip to the next clause and return only the values that were passed?有没有办法检查条件是否为 null 并跳到下一个子句并仅返回传递的值?

if I understand correctly, I think I should make several "Where" conditions, one for each condition, that is:如果我理解正确,我认为我应该制定几个“Where”条件,每个条件一个,即:

return _keys.Where(key => manufactor != string.Empty ? key.Manufactor == manufactor ? key.Manufactor != string.Empty)
            .Where(key => key.Type == type)
            .Where(key => key.ServiceType == service)
            .ToList();

You can also "exclude" or "include" filters if there is value to filter as I did with "key.Manufactor".如果有像我对“key.Manufactor”所做的过滤的价值,您还可以“排除”或“包含”过滤器。

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

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