29
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
IList<int> oneElementList = new List<int>() { 7 };
10
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
11
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
12
IList<string> emptyList = new List<string>();
13
14
Console.WriteLine("The only element in oneElementList: {0}", oneElementList.Single());
15
Console.WriteLine("The only element in oneElementList: {0}",
16
oneElementList.SingleOrDefault());
17
18
Console.WriteLine("Element in emptyList: {0}", emptyList.SingleOrDefault());
19
20
Console.WriteLine("The only element which is less than 10 in intList: {0}",
21
intList.Single(i => i < 10));
22
23
//Followings throw an exception
24
//Console.WriteLine("The only Element in intList: {0}", intList.Single());
25
//Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());
26
//Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());
27
28
}
29
}
Cached Result