Single
- Both First() and Single() will return single element from the source sequence.
- First() requires at least 1 element, that can be any element from the source squence
- But Single() has a special requirements for the sequence
- If Single() call without a lambda expression as input then the sequence should have only one element
int[] numbers = {5};
int found = numbers.Single();
Console.WriteLine(found);
//Outputint found = numbers.Single();
Console.WriteLine(found);
5
- If Single() call with a lambda expression as input then the sequence should have only one matching element for the given lambda expression
int[] numbers = {1, 2, 3};
int found = numbers.Single(x=> x == 2);
Console.WriteLine(found);
int found = numbers.Single(x=> x == 2);
Console.WriteLine(found);
- if both the cases doesn't met, Exception will be raised
SingleOrDefault
- Works same as FirstDefault
Element / ElementAtDefault
- Looks for the element at a particular index
string[] names = {"Name1", "Name2", "Name3", "Name4" };
string found = names.ElementAt(2);
Console.WriteLine(found);
//Output
Name3
string[] names = {"Name1", "Name2", "Name3", "Name4" };
string found = names.ElementAtOrDefault(5);
Console.WriteLine(found);
string found = names.ElementAt(2);
Console.WriteLine(found);
//Output
Name3
string[] names = {"Name1", "Name2", "Name3", "Name4" };
string found = names.ElementAtOrDefault(5);
Console.WriteLine(found);
No comments:
Post a Comment