C# SingleorDefault() Method

CsharpProgrammingServer Side Programming

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.


The following is an example showing the usage of SingleorDefault() method.


 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);


String found: one
String not found
Published on 14-Sep-2018 11:58:24