Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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# SingleorDefault() Method
The method returns a single specific element of a sequence. If the element is not present in the sequence, then the default value is returned.
We have two string arrays here.
string[] str1 = { "one" };
string[] str2 = { };
First array is checked for a single element, whereas the second array is empty and checked using SingleorDefault.
str2.AsQueryable().SingleOrDefault();
The following is an example showing the usage of SingleorDefault() method.
Example
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
string[] str1 = { "one" };
string[] str2 = { };
string res1 = str1.AsQueryable().Single();
Console.WriteLine("String found: "+res1);
string res2 = str2.AsQueryable().SingleOrDefault();
Console.WriteLine(String.IsNullOrEmpty(res2) ? "String not found" : res2);
}
}
Output
String found: one String not found
Advertisements