本文整理汇总了C#中System.Linq.Enumerable.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Enumerable.FirstOrDefault方法的具体用法?C# Enumerable.FirstOrDefault怎么用?C# Enumerable.FirstOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。
在下文中一共展示了Enumerable.FirstOrDefault方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1:
string[] names = { "Hartono, Tommy", "Adams, Terry",
"Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
string firstLongName = names.FirstOrDefault(name => name.Length > 20);
Console.WriteLine("The first long name is '{0}'.", firstLongName);
string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30);
Console.WriteLine(
"There is {0} name longer than 30 characters.",
string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a");
输出:
The first long name is 'Andersen, Henriette Thaulow'. There is not a name longer than 30 characters.
示例2:
int[] numbers = { };
int first = numbers.FirstOrDefault();
Console.WriteLine(first);
输出:
0
示例3:
List<int> months = new List<int> { };
// Setting the default value to 1 after the query.
int firstMonth1 = months.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.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