本文介绍了当Linq不返回任何内容时,返回一个空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下语句,目的是从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.

因此,调用ActiveMachinesInactiveMachines作为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).获得空值的唯一方法是调用FirstOrDefaultSingleOrDefault.

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不返回任何内容时,返回一个空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 08:48