本文整理匯總了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!