DefaultIfEmpty in LINQ

后端 未结 2 1082
别跟我提以往
别跟我提以往 2021-01-07 16:24

Can somebody explain how DefaultIfEmpty() can be used in LINQ. I have ready some material but still need something solid to see what the use of it is.<

2条回答
  •  [愿得一人]
    2021-01-07 17:03

    It basically returns a collection with a single element in case the source collection is empty.

    var numbers = new int[] {1, 2, 3};
    var aNumber = numbers.First();
    

    returns 1

    but

    var numbers = new int[];
    var aNumber = numbers.DefaultIfEmpty(12).Single();
    

    returns 12 as the collection is empty

提交回复
热议问题