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
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);
}
}