FirstOrDefault: Default value other than null

后端 未结 11 1188
-上瘾入骨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: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();
        //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;

提交回复
热议问题