FirstOrDefault:非null的默认值 [英] FirstOrDefault: Default value other than null

查看:113
本文介绍了FirstOrDefault:非null的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,在Linq中,方法FirstOrDefault()可以返回除空值以外的Default值.我还没有解决的是,当查询结果中没有任何项目时,此(和类似方法)可以返回null以外的其他东西.有什么特殊的方法可以设置它,以便在没有特定查询的值的情况下,返回一些预定义的值作为默认值?

As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null. What I haven't worked out is what kind of things other than null can be returned by this (and similar) method when there are no items in the query result. Is there any particular way that this can be set up so that if there is no value for a particular query some predefined value is returned as the default value?

推荐答案

一般情况,不仅限于值类型:

General case, not just for value types:

static class ExtensionsThatWillAppearOnEverything
{
    public static T IfDefaultGiveMe<T>(this T value, T alternate)
    {
        if (value.Equals(default(T))) return alternate;
        return value;
    }
}

var result = query.FirstOrDefault().IfDefaultGiveMe(otherDefaultValue);

同样,这无法真正判断您的序列中是否有 ,或者第一个值是默认值.

Again, this can't really tell if there was anything in your sequence, or if the first value was the default.

如果您对此很在意,可以做类似的事情

If you care about this, you could do something like

static class ExtensionsThatWillAppearOnIEnumerables
{
    public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
    {
        foreach(T t in source)
            return t;
        return alternate;
    }
}

并用作

var result = query.FirstOr(otherDefaultValue);

尽管Steak先生指出,.DefaultIfEmpty(...).First()也可以做到这一点.

although as Mr. Steak points out this could be done just as well by .DefaultIfEmpty(...).First().

这篇关于FirstOrDefault:非null的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆