本文整理汇总了C#中System.Linq.Enumerable.SingleOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Enumerable.SingleOrDefault方法的具体用法?C# Enumerable.SingleOrDefault怎么用?C# Enumerable.SingleOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。
在下文中一共展示了Enumerable.SingleOrDefault方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1:
string[] fruits1 = { "orange" };
string fruit1 = fruits1.SingleOrDefault();
Console.WriteLine(fruit1);
输出:
orange
示例2:
string[] fruits2 = { };
string fruit2 = fruits2.SingleOrDefault();
Console.WriteLine(
String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);
输出:
No such string!
示例3:
int[] pageNumbers = { };
// Setting the default value to 1 after the query.
int pageNumber1 = pageNumbers.SingleOrDefault();
if (pageNumber1 == 0)
{
pageNumber1 = 1;
}
Console.WriteLine("The value of the pageNumber1 variable is {0}", pageNumber1);
// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int pageNumber2 = pageNumbers.DefaultIfEmpty(1).Single();
Console.WriteLine("The value of the pageNumber2 variable is {0}", pageNumber2);
输出:
The value of the pageNumber1 variable is 1 The value of the pageNumber2 variable is 1
示例4:
string[] fruits = { "apple", "banana", "mango",
"orange", "passionfruit", "grape" };
string fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10);
Console.WriteLine(fruit1);
输出:
passionfruit
示例5:
string fruit2 =
fruits.SingleOrDefault(fruit => fruit.Length > 15);
Console.WriteLine(
String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);
输出:
No such string!