无涯教程-FirstOrDefault()方法

84 阅读1分钟

在LINQ中,FirstOrDefault()运算符用于返回列表/集合中的第一个元素。FirstOrDefault()运算符与LINQ First()运算符相同,唯一的区别是,如果列表不返回元素,则LINQ FirstOrDefault运算符方法将返回默认值。

FirstOrDefault方法的语法

下面是LINQ FirstOrDefault操作符的语法,用于返回列表中的第一个元素,或者如果列表不返回任何元素。

int result = objList.FirstOrDefault();

From the above syntax, we are trying to get the First element or default element from the "objList" collection by using LINQ FirstOrDefault() operator.

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();
    }

}

}

In the above example, we have two lists "ListObj", "objVal" and we are trying to get the first element from the lists by using the LINQ FirstOrDefault() method.

输出:

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




参考链接

www.learnfk.com/linq/linq-f…