Return empty collection when Linq where returns nothing

I use the following statement to get all the machine objects from the MachineList collection (type IEnumerable) that have MachineStatus i. The MachineList collection MachineList not always contain machines with i status.

Sometimes, when no machines have MachineStatus i, I would like to return an empty collection. My call to ActiveMachines (which is used first) works, but InactiveMachines does not work.

 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 seems that any MachineList enumeration will lead to subsequent MachineList enumerations to throw an exeception: Object reference not set to an instance of an object .

Therefore, it does not matter if the call to ActiveMachines or InactiveMachines called as a problem with the MachineList collection. This is especially troubling because I can break MachineList calls simply by listing it in a Watch before calling it in code. At the lowest level, MachineList implements NHibernate.IQuery , returned as IEnumerable . What causes MachineList to lose content after the initial enumeration?

+6
c # lambda linq ienumerable
source share
3 answers

Where returns an empty sequence if there are no matches; this is a perfectly valid sequence (not zero). The only way to get null is if you call FirstOrDefault or SingleOrDefault .

Are you sure the mistake is where you think it is?

 int?[] nums = { 1, 3, 5 }; var qry = nums.Where(i => i % 2 == 0); Console.WriteLine(qry == null); // false Console.WriteLine(qry.Count()); // 0 var list = qry.ToList(); Console.WriteLine(list.Count); // 0 var first = qry.FirstOrDefault(); Console.WriteLine(first == null); // true 
+7
source share

By default, Enumerable.Where already returns an empty IEnumerable<T> , not null. If you see "The reference to the object is not installed in the instance of the object." exceptions are most likely something else a problem.

Maybe MachineList null maybe? If you did not create it, you will get this exception when calling .Where(...)

+4
source share

Also, if you want to explicitly return an empty collection, this might help ...

 Enumerable.Empty<Machine>(); 
+2
source share