本文整理匯總了C#中System.Linq.Enumerable.Single方法的典型用法代碼示例。如果您正苦於以下問題:C# Enumerable.Single方法的具體用法?C# Enumerable.Single怎麽用?C# Enumerable.Single使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。
在下文中一共展示了Enumerable.Single方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1:
string[] fruits = { "apple", "banana", "mango",
"orange", "passionfruit", "grape" };
string fruit1 = fruits.Single(fruit => fruit.Length > 10);
Console.WriteLine(fruit1);
輸出:
passionfruit
示例2:
string fruit2 = null;
try
{
fruit2 = fruits.Single(fruit => fruit.Length > 15);
}
catch (System.InvalidOperationException)
{
Console.WriteLine(@"The collection does not contain exactly
one element whose length is greater than 15.");
}
Console.WriteLine(fruit2);
輸出:
The collection does not contain exactly one element whose length is greater than 15.
示例3:
string[] fruits1 = { "orange" };
string fruit1 = fruits1.Single();
Console.WriteLine(fruit1);
輸出:
orange
示例4:
string[] fruits2 = { "orange", "apple" };
string fruit2 = null;
try
{
fruit2 = fruits2.Single();
}
catch (System.InvalidOperationException)
{
Console.WriteLine("The collection does not contain exactly one element.");
}
Console.WriteLine(fruit2);
輸出:
The collection does not contain exactly one element.