31
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
//following throws error because list contains more than one element which is less than 100
15
Console.WriteLine("Element less than 100 in intList: {0}", intList.Single(i => i < 100));
16
17
//uncomment lines and check the result
18
//following throws error because list contains more than one element which is less than 100
19
//Console.WriteLine("Element less than 100 in intList: {0}", intList.SingleOrDefault(i => i < 100));
20
21
//following throws error because list contains more than one elements
22
//Console.WriteLine("The only Element in intList: {0}", intList.Single());
23
24
//following throws error because list contains more than one elements
25
//Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());
26
27
//following throws error because list does not contains any element
28
//Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());
29
30
}
31
}
Cached Result
122
159
110
175
106
163
130
151
120
100
142
133
187
169
189
112
175
142
181
103
159
110
175
106
163
130
151
120
100
142
133
187
169
189
112
175
142
181
103