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


LINQ FirstOrDefault()用法及代碼示例

在 LINQ 中, FirstOrDefault() 運算符用於返回列表/集合中的第一個元素。 FirstOrDefault() 運算符與 LINQ First() 運算符相同,唯一的區別是,如果列表不返回任何元素,則 LINQ FirstOrDefault 運算符方法將返回默認值。

FirstOrDefault 方法的語法

以下是 LINQ FirstOrDefault 運算符的語法,用於返回列表中的第一個元素,或者如果列表不返回任何元素。

int result = objList.FirstOrDefault();

根據上述語法,我們嘗試使用 LINQ FirstOrDefault() 運算符從 "objList" 集合中獲取第一個元素或默認元素。

LINQ FirstOrDefault() 運算符示例

以下是在方法語法中使用 LINQ FirstOrDefault() 運算符返回列表中的第一個元素或在列表不包含任何值的情況下的示例。

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
    class Program1
    {
        static void Main(string[] args)
        {
//Create an array ListObj type of int and objVal type of int
            int[] ListObj = { 1, 2, 3, 4, 5 };
            int[] objVal = { };
/*FirstOrDefault() method is used to return the first element from the
    list and the list not contain any element will return the default value.*/
            int result = List.FirstOrDefault();
            int val = objVal.FirstOrDefault();
            Console.WriteLine("Element from the List1:{0}", result);
            Console.WriteLine("Element from the List2:{0}", val);
            Console.ReadLine();

        }

    }
}

在上麵的示例中,我們有兩個列表 "ListObj"、"objVal",我們嘗試使用 LINQ FirstOrDefault() 方法從列表中獲取第一個元素。

輸出:

LINQ FirstOrDefault() Method

查詢語法中的 LINQ FirstOrDefault () 運算符示例

以下是在查詢語法中使用 LINQ FirstOrDefault() 運算符返回列表中的第一個元素或在列表不包含任何值的情況下的示例。

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program1
    {
        static void Main(string[] args)
        {


            int[] ListOb = { 1, 2, 3, 4, 5 };

            int[] ValOb = { };

            int result = (from l in ListOb select l).FirstOrDefault();

            int val = (from x in ValOb

                       select x).FirstOrDefault();

            Console.WriteLine("Element from the List1:{0}", result);

            Console.WriteLine("Element from the List2:{0}", val);

            Console.ReadLine();

        }

    }

    }

輸出:

LINQ FirstOrDefault() Method



相關用法


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