
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
C# Linq LastorDefault Method
Use the LastorDefault() method to return the last element of a sequence or a default value if element isn’t there.
The following is our empty list.
List<double> val = new List<double> { };
Now the following will not be able to display the last element since the list is empty. Therefore, the default would get display and error won’t be shown.
val.AsQueryable().LastOrDefault();
The following is the code.
Example
using System; using System.Collections.Generic; using System.Linq; class Demo { static void Main() { List<double> val = new List<double> { }; double d = val.AsQueryable().LastOrDefault(); Console.WriteLine("Default Value = "+d); if (d == 0.0D) { d = 0.1D; } Console.WriteLine("Default Value changed = "+d); } }
Output
Default Value = 0 Default Value changed = 0.1
- Related Articles
- What is the difference between Last() and LastOrDefault() in Linq C#?
- C# Linq Distinct() Method
- C# Linq Where Method
- C# Linq Intersect Method
- C# Linq FirstorDefault Method
- C# Linq Reverse Method
- C# Linq Select Method
- C# Linq SelectMany Method
- C# Linq Skip() Method
- C# Linq SkipLast Method
- C# Linq Sum() Method
- C# Linq TakeWhile() Method
- C# Linq ThenBy Method
- C# Linq Zip Method
- C# Linq Contains Method

Advertisements