SingleOrDefault is similar to Single. On empty collections, it returns the default value for the type. With it you receive the single matching element, or the default value if no element is found.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Prototype{
class Example
{
static void Main()
{
int[] array = { 1, 2, 3,4,5,6,7,8,9 };
// Default is returned 0 if no element found.
int a = array.SingleOrDefault(element => element == 10);
Console.WriteLine(a);
// Value is returned if one is found.
int b = array.SingleOrDefault(element => element == 8);
Console.WriteLine(b);
Console.ReadLine();
}
}
}
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
SingleOrDefault is similar to Single. On empty collections, it returns the default value for the type. With it you receive the single matching element, or the default value if no element is found.