FirstOrDefault: Default value other than null

后端 未结 11 1198
-上瘾入骨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:05

    I just had a similar situation and was looking for a solution that allows me to return an alternative default value without taking care of it at the caller side every time I need it. What we usually do in case Linq does not support what we want, is to write a new extension that takes care of it. That´s what I did. Here is what I came up with (not tested though):

    public static class EnumerableExtensions
    {
        public static T FirstOrDefault(this IEnumerable items, T defaultValue)
        {
            foreach (var item in items)
            {
                return item;
            }
            return defaultValue;
        }
    
        public static T FirstOrDefault(this IEnumerable items, Func predicate, T defaultValue)
        {
            return items.Where(predicate).FirstOrDefault(defaultValue);
        }
    
        public static T LastOrDefault(this IEnumerable items, T defaultValue)
        {
            return items.Reverse().FirstOrDefault(defaultValue);
        }
    
        public static T LastOrDefault(this IEnumerable items, Func predicate, T defaultValue)
        {
            return items.Where(predicate).LastOrDefault(defaultValue);
        }
    }
    

提交回复
热议问题