本文整理汇总了C#中System.Linq.Queryable.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Queryable.FirstOrDefault方法的具体用法?C# Queryable.FirstOrDefault怎么用?C# Queryable.FirstOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。
在下文中一共展示了Queryable.FirstOrDefault方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1:
// Create an empty array.
int[] numbers = { };
// Get the first item in the array, or else the
// default value for type int (0).
int first = numbers.AsQueryable().FirstOrDefault();
Console.WriteLine(first);
输出:
0
示例2:
List<int> months = new List<int> { };
// Setting the default value to 1 after the query.
int firstMonth1 = months.AsQueryable().FirstOrDefault();
if (firstMonth1 == 0)
{
firstMonth1 = 1;
}
Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1);
// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int firstMonth2 = months.AsQueryable().DefaultIfEmpty(1).First();
Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2);
输出:
The value of the firstMonth1 variable is 1 The value of the firstMonth2 variable is 1
示例3:
string[] names = { "Hartono, Tommy", "Adams, Terry",
"Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
// Get the first string in the array that is longer
// than 20 characters, or the default value for type
// string (null) if none exists.
string firstLongName =
names.AsQueryable().FirstOrDefault(name => name.Length > 20);
Console.WriteLine("The first long name is '{0}'.", firstLongName);
// Get the first string in the array that is longer
// than 30 characters, or the default value for type
// string (null) if none exists.
string firstVeryLongName =
names.AsQueryable().FirstOrDefault(name => name.Length > 30);
Console.WriteLine(
"There is {0} name that is longer than 30 characters.",
string.IsNullOrEmpty(firstVeryLongName) ? "NOT a" : "a");
输出:
The first long name is 'Andersen, Henriette Thaulow'. There is NOT a name that is longer than 30 characters.
示例4: Main
//引入命名空间
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 1, 3, 5, 7, 9 };
var query = numbers.FirstOrDefault(n => n % 2 == 0);
Console.WriteLine("The first even element in the sequence");
Console.Write(query);
Console.WriteLine("The last odd element in the sequence");
query = numbers.LastOrDefault(n => n % 2 == 1);
Console.Write(query);
}
}