本文整理汇总了C#中System.Linq.Queryable.SingleOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Queryable.SingleOrDefault方法的具体用法?C# Queryable.SingleOrDefault怎么用?C# Queryable.SingleOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。
在下文中一共展示了Queryable.SingleOrDefault方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1:
// Create two arrays. The second is empty.
string[] fruits1 = { "orange" };
string[] fruits2 = { };
// Get the only item in the first array, or else
// the default value for type string (null).
string fruit1 = fruits1.AsQueryable().SingleOrDefault();
Console.WriteLine("First Query: " + fruit1);
// Get the only item in the second array, or else
// the default value for type string (null).
string fruit2 = fruits2.AsQueryable().SingleOrDefault();
Console.WriteLine("Second Query: " +
(String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2));
输出:
First Query: orange Second Query: No such string!
示例2:
int[] pageNumbers = { };
// Setting the default value to 1 after the query.
int pageNumber1 = pageNumbers.AsQueryable().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.AsQueryable().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
示例3:
string[] fruits = { "apple", "banana", "mango",
"orange", "passionfruit", "grape" };
// Get the single string in the array whose length is greater
// than 10, or else the default value for type string (null).
string fruit1 =
fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 10);
Console.WriteLine("First Query: " + fruit1);
// Get the single string in the array whose length is greater
// than 15, or else the default value for type string (null).
string fruit2 =
fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 15);
Console.WriteLine("Second Query: " +
(String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2));
输出:
First Query: passionfruit Second Query: No such string!
示例4: Main
//引入命名空间
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
var query = numbers.SingleOrDefault(n => n > 9);
Console.Write(query);
}
}