Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • LINQ - Get Started
  • What is LINQ
  • Why LINQ
  • LINQ API
  • LINQ Query Syntax
  • LINQ Method Syntax
  • Lambda Expression
  • Standard Query Operators
  • Where
  • OfType
  • OrderBy
  • ThenBy
  • GroupBy, ToLookup
  • Join
  • GroupJoin
  • Select
  • All, Any
  • Contains
  • Aggregate
  • Average
  • Count
  • Max
  • Sum
  • ElementAt, ElementAtOrDefault
  • First, FirstOrDefault
  • Last, LastOrDefault
  • Single, SingleOrDefault
  • SequenceEqual
  • Concat
  • DefaultIfEmpty
  • Empty, Range, Repeat
  • Distinct
  • Except
  • Intersect
  • Union
  • Skip, SkipWhile
  • Take, TakeWhile
  • Conversion Operators
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Element Operators : Last & LastOrDefault

The Last() and LastOrDefault() extension methods returns the last element from the collection.

Element OperatorsDescription
Last()Returns the last element from a collection, or the last element that satisfies a condition. Throws exception if no element found.
LastOrDefault()Returns the last element from a collection, or the last element that satisfies a condition. Returns a default value if no element found.
Method Signature:
public static TSource Last<TSource>(this IEnumerable<TSource> source);public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source);public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

The Last() method returns the last element from a collection, or the last element that satisfies the specified condition using lambda expression or Func delegate. If a given collection is empty or does not include any element that satisfied the condition then it will throw InvalidOperation exception.

The LastOrDefault() method does the same thing as the Last() method. The only difference is that it returns default value of the data type of a collection if a collection is empty or doesn't find any element that satisfies the condition.

Example: LINQ Last() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
		
Console.WriteLine("Last Element in intList: {0}", intList.Last());

Console.WriteLine("Last Even Element in intList: {0}", intList.Last(i => i % 2 == 0));

Console.WriteLine("Last Element in strList: {0}", strList.Last());

Console.WriteLine("emptyList.Last() throws an InvalidOperationException");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.Last());
Try it
Output:
Last Element in intList: 87
Last Even Element in intList: 50
Last Element in strList: Five
emptyList.Last() throws an InvalidOperationException
-------------------------------------------------------------
Run-time exception: Sequence contains no elements...

The following example demonstrates the LastOrDefault() method.

Example: LINQ LastOrDefault() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
		
Console.WriteLine("Last Element in intList: {0}", intList.LastOrDefault());

Console.WriteLine("Last Even Element in intList: {0}",
                                 intList.LastOrDefault(i => i % 2 == 0));

Console.WriteLine("Last Element in strList: {0}", strList.LastOrDefault());

Console.WriteLine("Last Element in emptyList: {0}", emptyList.LastOrDefault());
Try it
Output:
Last Element in intList: 7
Last Even Element in intList: 50
Last Element in strList: Five
Last Element in emptyList:

Be careful while specifying condition in the Last() or LastOrDefault() methods. The Last() method will throw an exception if a collection does not include any element that satisfies the specified condition or includes null element.

If a collection includes null element then the LastOrDefault() throws an exception while evaluting the specified condition.

Example: LINQ Last() & LastOrDefault() - C#
IList<string> strList1 = new List<string>() { "Two", "Three", "Four", "Five" };
IList<string> strList2 = new List<string>() { null, "Two", "Three", "Four", "Five" };		

Console.WriteLine(strList1.LastOrDefault(s => s.Contains("T")));
Console.WriteLine(strList2.LastOrDefault(s => s.Contains("T")));// throws an exception
Try it
Output:
Run-time exception: Sequence contains no matching element
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.