LINQ in C# - Non-Deferred Operator Examples- (First, FirstOrDefault, Last, LastOrDefault) - Equality

First/Last - Type 1 Example 1

  • First will raise error(System.InvalidOperationException: 'Sequence contains no matching element'),  if cannot find element in the first position that is no element in the squence
string[] presidents = { "Adams", "Arthur", "Buchanan", "Bush", "Carter",
                                    "Cleveland", "Clinton", "Coolidge", "Eisenhower",
                                    "Fillmore", "Ford", "Garfield", "Grant", "Harding",
                                    "Harrison", "Hayes", "Hoover", "Jackson", "Jefferson",
                                    "Johnson", "Kennedy", "Lincoln", "Madison", "McKinley",
                                    "Monroe", "Nixon", "Obama", "Pierce", "Polk", "Reagan",
                                    "Roosevelt", "Taft", "Taylor", "Truman", "Tyler", "Van Buren",
                                    "Washington", "Wilson" };

            Console.WriteLine(presidents.First());
//Output
Adams

First/Last - Type 2 Example 1

 Console.WriteLine(presidents.First(x=> x.StartsWith("H")));

//Output
Harding

FirstOrDefault/LastOrDefault - Example 1

  • Return first element in the sequence if not found return default value of the return type
string foundName = presidents.Take(0).FirstOrDefault();
Console.WriteLine(foundName);


string found = presidents.FirstOrDefault(x => x.Length>20);
            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...