LINQ in C# - Non-Deferred Operator Examples- First vs Single/SingleDefault - ElementAt/ElementAtOrDefault- Equality

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);
//Output
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);
    • 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);

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...