Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# firstordefault

作者:整整ー世♂陰霾そ   发布日期:2025-12-26   浏览:59

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // 定义一个整数数组
        int[] numbers = { 1, 2, 3, 4, 5 };

        // 使用FirstOrDefault查找第一个大于10的元素,如果不存在则返回默认值(0)
        int result = numbers.FirstOrDefault(num => num > 10);

        // 输出结果
        Console.WriteLine("The first number greater than 10 is: " + result);

        // 如果数组为空或没有满足条件的元素,则返回默认值
        int[] emptyNumbers = { };
        int emptyResult = emptyNumbers.FirstOrDefault();
        Console.WriteLine("The first number in an empty array is: " + emptyResult);
    }
}

解释说明:

  • FirstOrDefault 是 LINQ 中的一个扩展方法,用于返回序列中的第一个元素。如果没有元素满足条件或者序列为空,则返回该类型的默认值(对于引用类型是 null,对于值类型是 default(T),例如 int 的默认值是 0)。
  • 在示例代码中,我们定义了一个整数数组 numbers 并使用 FirstOrDefault 查找第一个大于 10 的元素。由于数组中没有大于 10 的元素,因此返回默认值 0
  • 另外,我们还演示了当数组为空时调用 FirstOrDefault 的情况,此时也会返回默认值 0

上一篇:c# configureawait

下一篇:c# memorycache

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站