Reputation: 93
var items = context.Items.Where(x => x.IsActive=true).ToList();
Why is correct syntax and working query?
Upvotes: 3
Views: 214
Reputation: 563
Why it is working?
I think works because 'x.IsActive = true' will always evaluate to true. So it's not syntactically incorrect.
In other words the code is saying:
So as all items are set to true it will return everything.
Upvotes: 1
Reputation: 16609
This is a very subtle bug in the code. The Where
Func needs to return a bool
to be valid, but you are setting the value, rather than comparing it, so there's nothing to return, yes?
The code compiles because when you assign a value in c#, e.g. x = 1
that expression is evaluated, and therefore returned, as the value which was assigned (1
).
People sometimes use this to lazily instantiate a readonly property, e.g.
private Foo myFoo;
public Foo FooInstance
{
// set myFoo to the existing instance or a new instance
// and return the result of the "myFoo ?? new Foo()" expression
get { return myFoo = myFoo ?? new Foo(); }
}
or assign the same value to multiple variables:
// set z to 1
// set y to result of "z = 1"
// set x to result of "y = z = 1"
x = y = z = 1;
So what you are doing for each entry in the list is set IsActive
to true
and return that same true
from the function. So then you end up with a new List containing all entries, and all of them have been changed to Active.
If you were using a property in the Where
which is not a bool
, such as an int
, you would get a compilation error:
Cannot implicitly convert type 'int' to 'bool'.
See this as an example (https://dotnetfiddle.net/9S9NAV)
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var foos = new List<Foo>()
{
new Foo(true, 1),
new Foo(false, 2)
};
// works
var actives = foos.Where(x => x.IsActive=true).ToList();
// returns 2, not 1!
Console.WriteLine(actives.Count);
// compile error
var ages = foos.Where(x => x.Age = 1).ToList();
}
}
public class Foo {
public Foo(bool active, int age)
{
this.IsActive = active;
this.Age = age;
}
public bool IsActive { get; set; }
public int Age { get; set; }
}
Upvotes: 3
Reputation: 172428
Your example is working as your are assigning the value and not comparing value which is syntactically correct and hence it compiles and executes correctly. Note that = is used for assignment and == is used for comparison.
When you say:
var items = context.Items.Where(x => x.IsActive=true).ToList();
In this you are not comparing rather assigning the true
value to IsActive
which is fine for the compiler and hence you find it working.
Upvotes: 1
Reputation: 29016
use ==
for checking condition
var items = context.Items.Where(x => x.IsActive==true).ToList();
Or
var items = context.Items.Where(x => x.IsActive).ToList();
Upvotes: 0