Return an empty collection when Linq where returns nothing
Posted
by ahsteele
on Stack Overflow
See other posts from Stack Overflow
or by ahsteele
Published on 2009-11-30T22:10:24Z
Indexed on
2010/04/19
12:33 UTC
Read the original article
Hit count: 324
I am using the below statement with the intent of getting all of the machine objects from the MachineList
collection (type IEnumerable) that have a MachineStatus
of i. The MachineList
collection will not always contain machines with a status of i.
At times when no machines have a MachineStatus
of i I'd like to return an empty collection. My call to ActiveMachines
(which is used first) works but InactiveMachines
does not.
public IEnumerable<Machine> ActiveMachines
{
get
{
return Customer.MachineList
.Where(m => m.MachineStatus == "a");
}
}
public IEnumerable<Machine> InactiveMachines
{
get
{
return Customer.MachineList
.Where(m => m.MachineStatus == "i");
}
}
Edit
Upon further examination it appears that any enumeration of MachineList
will cause subsequent enumerations of MachineList
to throw an exeception: Object reference not set to an instance of an object
.
Therefore, it doesn't matter if a call is made to ActiveMachines
or InactiveMachines
as its an issue with the MachineList
collection. This is especially troubling because I can break calls to MachineList
simply by enumerating it in a Watch before it is called in code. At its lowest level MachineList
implements NHibernate.IQuery
being returned as an IEnumerable
. What's causing MachineList
to lose its contents after an initial enumeration?
© Stack Overflow or respective owner