本文整理匯總了C#中System.Linq.Enumerable.LastOrDefault方法的典型用法代碼示例。如果您正苦於以下問題:C# Enumerable.LastOrDefault方法的具體用法?C# Enumerable.LastOrDefault怎麽用?C# Enumerable.LastOrDefault使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。
在下文中一共展示了Enumerable.LastOrDefault方法的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1:
string[] fruits = { };
string last = fruits.LastOrDefault();
Console.WriteLine(
String.IsNullOrEmpty(last) ? "<string is null or empty>" : last);
輸出:
示例2:
List<int> daysOfMonth = new List<int> { };
// Setting the default value to 1 after the query.
int lastDay1 = daysOfMonth.LastOrDefault();
if (lastDay1 == 0)
{
lastDay1 = 1;
}
Console.WriteLine("The value of the lastDay1 variable is {0}", lastDay1);
// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int lastDay2 = daysOfMonth.DefaultIfEmpty(1).Last();
Console.WriteLine("The value of the lastDay2 variable is {0}", lastDay2);
輸出:
The value of the lastDay1 variable is 1 The value of the lastDay2 variable is 1
示例3:
double[] numbers = { 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 };
double last50 = numbers.LastOrDefault(n => Math.Round(n) == 50.0);
Console.WriteLine("The last number that rounds to 50 is {0}.", last50);
double last40 = numbers.LastOrDefault(n => Math.Round(n) == 40.0);
Console.WriteLine(
"The last number that rounds to 40 is {0}.",
last40 == 0.0 ? "<DOES NOT EXIST>" : last40.ToString());
輸出:
The last number that rounds to 50 is 50.2. The last number that rounds to 40 is.