Class
public class Employee
{
public string EmployeeID { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public bool Employed { get; set; }
public bool Administrator { get; set; }
}
Linq statement
var adminlist = db.Employees.Where(x => x.Administrator).Select(x => x.Administrator).ToList();
I'm sure this is a stupid question but please can anybody tell me why the above returns null? I've tried this too:
var adminlist = db.Employees.Where(x => x.Administrator).ToList();
If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.
It will return an empty enumerable. It won't be null.
By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
Your second query will NEVER return null unless the database is inaccessible. IEnumerable.ToList()
will never return null
, only an empty list if no items were found. It will throw an exception if the source is null.
Your problem lies elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With