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

 Live Demo

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements