- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements