
- 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 FirstorDefault Method
Use the FirstorDefault() method to return the first 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, we cannot display the first element, since it is an empty collection. For that, use the FirstorDefault() method to display the default value.
val.AsQueryable().FirstOrDefault();
The following is the complete example.
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().FirstOrDefault(); 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
- C# Linq Distinct() Method
- C# Linq Where Method
- C# Linq Intersect 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 LastorDefault Method
- C# Linq Zip Method
- C# Linq Contains Method
- C# Linq Count method

Advertisements