个性化阅读
专注于IT技术分析

LINQ DefaultfEmpty()方法

在LINQ中, 如果列表/集合包含null或空值, 则使用DefaultfEmpty()方法返回默认值。否则, 它将返回集合中序列中的元素。

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

var result = List1.DefaultIfEmpty();

从以上语法中, 我们使用LINQ DefaultfEmpty方法获取项目列表。

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, 并且尝试使用LINQ DefaultfEmpty()方法从这两个列表中获取元素。

输出

LINQ DefaultfEmpty()方法

赞(0)
未经允许不得转载:srcmini » LINQ DefaultfEmpty()方法

评论 抢沙发

评论前必须登录!