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
Copied over from comment by @sloth
Instead of YourCollection.FirstOrDefault()
, you could use YourCollection.DefaultIfEmpty(YourDefault).First()
for example.
Example:
var viewModel = new CustomerDetailsViewModel
{
MainResidenceAddressSection = (MainResidenceAddressSection)addresses.DefaultIfEmpty(new MainResidenceAddressSection()).FirstOrDefault( o => o is MainResidenceAddressSection),
RiskAddressSection = addresses.DefaultIfEmpty(new RiskAddressSection()).FirstOrDefault(o => !(o is MainResidenceAddressSection)),
};
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;
}
}
and use as
var result = query.FirstOr(otherDefaultValue);
although as Mr. Steak points out this could be done just as well by .DefaultIfEmpty(...).First()
.
You can use DefaultIfEmpty followed by First:
T customDefault = ...;
IEnumerable<T> mySequence = ...;
mySequence.DefaultIfEmpty(customDefault).First();
Actually, I use two approaches to avoid NullReferenceException
when I'm working with collections:
public class Foo
{
public string Bar{get; set;}
}
void Main()
{
var list = new List<Foo>();
//before C# 6.0
string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;
//C# 6.0 or later
var barCSharp6 = list.FirstOrDefault()?.Bar;
}
Use ?.
or ?[
to test if is null before perform a member access Null-conditional Operators documentation
Example:
var barCSharp6 = list.FirstOrDefault()?.Bar;
Use DefaultIfEmpty()
to retrieve a default value if the sequence is empty.MSDN Documentation
Example:
string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;
Use DefaultIfEmpty()
instead of FirstOrDefault()
.