FirstOrDefault: Default value other than null

后端 未结 11 1184
-上瘾入骨i
-上瘾入骨i 2020-12-12 21:37

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 wha

11条回答
  •  旧巷少年郎
    2020-12-12 22:09

    I know its been a while but Ill add to this, based on the most popular answer but with a little extension Id like to share the below:

    static class ExtensionsThatWillAppearOnIEnumerables
    {
        public static T FirstOr(this IEnumerable source, Func predicate, Func alternate)
        {
            var thing = source.FirstOrDefault(predicate);
            if (thing != null)
                return thing;
            return alternate();
        }
    }
    

    This allows me to call it inline as such with my own example I was having issues with:

    _controlDataResolvers.FirstOr(x => x.AppliesTo(item.Key), () => newDefaultResolver()).GetDataAsync(conn, item.ToList())
    

    So for me I just wanted a default resolver to be used inline, I can do my usual check and then pass in a function so a class isn't instantiated even if unused, its a function to execute when required instead!

提交回复
热议问题