本文介绍了当SingleOrDefault返回null时的LINQ新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的方法:

    #region Fields

    private Collection<Address> _addresses;

    #endregion

    #region Public methods

    public Address DeliveryAddress()
    {
        if (_addresses == null)
            if (this.Id > 0)
                _addresses = Core.Data.Addresses.GetClient(this.Id);

        return _addresses.SingleOrDefault(x => x.TypeId == AddressType.Delivery);
    }

    public Address InvoiceAddress()
    {
        if (_addresses == null)
            if (this.Id > 0)
                _addresses = Core.Data.Addresses.GetClient(this.Id);

        return _addresses.SingleOrDefault(x => x.TypeId == AddressType.Invoice);
    }

    #endregion

如您所见,我试图为DeliveryAddress返回一个结果,为InvoiceAddress返回一个结果.我的问题是,如果SingleOrDefault返回null,我希望链接表达式创建Address()的新实例.我真的是linq的新手,所以我不确定SingleOrDefault是否是我应该使用的正确表达式.

As you can see I trying to return one result for a DeliveryAddress and one result for an InvoiceAddress. My problem is that I would like the link expression to create a new instance of Address() if SingleOrDefault returns null.I am really new to linq, so I am not sure whether SingleOrDefault is the correct expression I should be using.

推荐答案

您可以使用 DefaultIfEmpty 并将该实例用作默认值:

You could use DefaultIfEmpty and use that instance as default value:

return _addresses.Where(x => x.TypeId == AddressType.Delivery)
                 .DefaultIfEmpty(new Adress())
                 .Single();

这篇关于当SingleOrDefault返回null时的LINQ新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:42