在LINQ中,如果列表/集合包含NULL或空值,则DefaultfEmpty()方法用于在这种情况下返回默认值;否则,它将从集合中的序列返回元素。
当LINQ DefaultfEmpty()方法返回空或空值时使用LINQ DefaultfEmpty()方法获取元素列表的语法。
var result = List1.DefaultIfEmpty();
根据上述语法,我们使用LINQDefaultfEmpty方法获取项目列表。
下面是LINQ DefaultfEmpty()方法的示例,当我们在列表/集合中找不到任何元素时,它从列表中获取元素或返回值。
using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Programme2 { static void Main(string[] args) { //create an array 'b' int[] b = { }; int[] a = { 1, 2, 3, 4, 5 }; //with the help of DefaultfEmpty try to fetch the value from both of the list var result = a.DefaultIfEmpty(); var result1 = b.DefaultIfEmpty(); Console.WriteLine("----List1 with Values----"); //with the help of foreach loop we will print the value of 'result' variable foreach (var val1 in result) { Console.WriteLine(val1); } Console.WriteLine("---List2 without Values---"); //with the help of foreach loop we will print the value of 'result1' variable foreach (var val2 in result1) { Console.WriteLine(val2); } Console.ReadLine(); } } }
在上面的示例中,我们有两个列表a和b,我们试图使用LINQDefaultfEmpty()方法从这两个列表中获取元素。
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)