當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


LINQ DefaultfEmpty()用法及代碼示例

在 LINQ 中,如果列表/集合包含空值或空值,則 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() Method



相關用法


注:本文由純淨天空篩選整理自 LINQ DefaultfEmpty() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。