DefaultEmpty()方法

DefaultEmpty()方法 首页 / LinQ入门教程 / DefaultEmpty()方法

在LINQ中,如果列表/集合包含NULL或空值,则DefaultfEmpty()方法用于在这种情况下返回默认值;否则,它将从集合中的序列返回元素。

当LINQ DefaultfEmpty()方法返回空或空值时使用LINQ DefaultfEmpty()方法获取元素列表的语法。

var result = List1.DefaultIfEmpty();

根据上述语法,我们使用LINQDefaultfEmpty方法获取项目列表。

LINQ DefaultfEmpty()方法示例

下面是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()方法从这两个列表中获取元素。

输出:

LINQ DefaultfEmpty() Method




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

程序员的数学基础课 -〔黄申〕

安全攻防技能30讲 -〔何为舟〕

Electron开发实战 -〔邓耀龙〕

如何落地业务建模 -〔徐昊〕

去无方向的信 -〔小麥〕

网络排查案例课 -〔杨胜辉〕

说透低代码 -〔陈旭〕

Dubbo源码剖析与实战 -〔何辉〕

结构会议力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)