AND Operator cannot work with bool and string

2019-07-12 08:22发布

问题:

I have a LINQ2SQL statement where I am using two criteria:

var query1 = from r in dt.Test
                                where r.ID == 92 
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?

回答1:

Try replacing your = signs with ==

var query1 = from r in dt.Test
                            where r.ID == 92 
                            && r.Status == "I"
                            select r.ID && r.Status == "I"

Remember that = in C# is the assignment operator, and == is the equality operator. As someone who regularly flips between C# and VB.NET, I often come unstuck here!



回答2:

You have a single equals sign r.Status = '"I", should be r.Status == '"I"



回答3:

You mean == in place of =; the assignment expression (as opposed to the equality operator) is confusing things; instead of returning a bool, the result of r.Status = "I" is a string... "I"

var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select r.ID;

(not quite sure what to make of the last part of your select, so I omitted it)



回答4:

  1. = is used for assignment and == is used for equality.
  2. I am not sure what result you're expecting, but select r.ID && r.Status == "I" (even with 2 equal signs) is not valid in any case.

Depending on what you want to select, if the result is the amount of the rows qualifying for your search consider using Count(). If you want to select these two values, use a POCO class or an anonymous type:

var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select new { ID = r.ID, Status = r.Status };


回答5:

var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select r.ID && r.Status == "I";