本文整理汇总了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.