问题描述
我正在使用以下语句,目的是从MachineList
集合(类型IEnumerable)中获取所有具有 i 的计算机对象. MachineList
集合并不总是包含状态为 i 的计算机.
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.
在没有机器的MachineStatus
为 i 的时候,我想返回一个空集合.我对ActiveMachines
的调用(首先使用)有效,但InactiveMachines
无效.
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");
}
}
修改
进一步检查似乎发现,MachineList
的任何枚举都会导致随后的MachineList
枚举引发错误:Object reference not set to an instance of an object
.
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
.
因此,调用ActiveMachines
或InactiveMachines
作为MachineList
集合的问题并不重要.这尤其令人不安,因为我可以通过在代码中调用MachineList
之前简单地通过在Watch中枚举它来中断对MachineList
的调用.在最低级别,MachineList
实现NHibernate.IQuery
作为IEnumerable
返回.是什么原因导致MachineList
在初始枚举后丢失其内容?
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?
推荐答案
Where
如果没有匹配项,则返回空序列;否则,返回空序列.这是一个完全有效的序列(不为null).获得空值的唯一方法是调用FirstOrDefault
或SingleOrDefault
.
Where
returns an empty sequence if there are no matches; this is a perfectly valid sequence (not null). The only way you'd get a null is if you call FirstOrDefault
or SingleOrDefault
.
您确定错误位于您认为的位置吗?
Are you sure the bug 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
这篇关于当Linq不返回任何内容时,返回一个空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!