简体   繁体   中英

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:

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. So I decided to move everything to a list in C # and do the search with lambdas functions.

This is the function with lambda expression:

 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.

When I leave one or two of the parameters null, it returns no value. 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?

if I understand correctly, I think I should make several "Where" conditions, one for each condition, that is:

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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