Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '&&' cannot be applied to operands of type 'lambda expression' and 'lambda expression

I want to retrive all the records that have the IP or MAC addresses or if any of these are Null, so i wrote my method as follow:-

public IQueryable<Technology> AdvanceSearch(string ip = null, string mac = null, int techtype) 
        {
            var relatedresourcesID = entities.NetworkInfoes
                .Where((a => String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)))
                .Where(a2 => String.IsNullOrEmpty(mac) || a2.MACADDRESS.StartsWith(mac)).Select(a3=>a3.WORKSTATIONID);
//code goes here

but i am not sure how will EF transalte the .where ; will it apply the second .Where() only after applying the first .Where clause ?

second question, how i can apply all the checks to be inside one .Where()??

I have tried to re-write my method as follow:-

var relatedresourcesID = entities.NetworkInfoes
                .Where((a => String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)) && (a2 => String.IsNullOrEmpty(mac) || a2.MACADDRESS.StartsWith(mac)) )
                .Select(a3=>a3.WORKSTATIONID);

but i will get the following error :-

Error 18 Operator '&&' cannot be applied to operands of type 'lambda expression' and 'lambda expression' C:\Users\Administrator\documents\visual studio 2012\Projects\TMS\TMS\Models\Repository.cs 914 24 TMS

like image 837
john Gu Avatar asked Oct 25 '13 23:10

john Gu


People also ask

What is a function of an operator?

An operator is used to manipulate individual data items and return a result. These items are called operands or arguments.

What are the 7 types of operators?

In Python, there are seven different types of operators: arithmetic operators, assignment operators, comparison operators, logical operators, identity operators, membership operators, and boolean operators.


1 Answers

You should pass single lambda expression into where operator:

var relatedresourcesID = entities.NetworkInfoes
       .Where(a => (String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)) &&
                   (String.IsNullOrEmpty(mac) || a.MACADDRESS.StartsWith(mac)))
       .Select(a => a.WORKSTATIONID);

NOTE: You don't need to assign new names of parameter in each operator - these scopes do not overlap.

Also don't forget about declarative query syntax, which is more readable (IMHO) and will not use lambdas at all:

var relatedresourcesID = 
     from a in entities.NetworkInfoes
     where (String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)) &&
           (String.IsNullOrEmpty(mac) || a.MACADDRESS.StartsWith(mac))
     select a.WORKSTATIONID;
like image 132
Sergey Berezovskiy Avatar answered Nov 14 '22 23:11

Sergey Berezovskiy