FirstOrDefault: Default value other than null

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

    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)),
        };
    
    0 讨论(0)
  • 2020-12-12 22:12

    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().

    0 讨论(0)
  • 2020-12-12 22:14

    You can use DefaultIfEmpty followed by First:

    T customDefault = ...;
    IEnumerable<T> mySequence = ...;
    mySequence.DefaultIfEmpty(customDefault).First();
    
    0 讨论(0)
  • 2020-12-12 22:15

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

    For C# 6.0 or later:

    Use ?. or ?[ to test if is null before perform a member access Null-conditional Operators documentation

    Example: var barCSharp6 = list.FirstOrDefault()?.Bar;

    C# older version:

    Use DefaultIfEmpty() to retrieve a default value if the sequence is empty.MSDN Documentation

    Example: string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;

    0 讨论(0)
  • 2020-12-12 22:15

    Use DefaultIfEmpty() instead of FirstOrDefault().

    0 讨论(0)
提交回复
热议问题