- 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
How to handle empty collections in C#
To handle empty collections, use the DefaultIfEmpty() method in C#.
If an array is empty, then using this method will show the default method instead of displaying an error.
Let’s say we have an empty list.
List<float> myList = new List<float>();
Now, use DefaultIfEmpty() method to display the default value.
myList.DefaultIfEmpty();
Example
using System; using System.Linq; using System.Collections.Generic; class Demo { static void Main() { List<float> myList = new List<float>(); var res = myList.DefaultIfEmpty(); foreach (var a in res) { Console.WriteLine(a); } } }
Output
0
Advertisements