Advertise with us

Use SingleOrDefault in Linq.

We want to use SingleOrDefault in Linq. how to use this please help me.
Last updated:3/18/2016 11:19:08 PM

1 Answers

Aditya Patel
Aditya Patel

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

}

}

}

Last updated:3/18/2016 11:19:08 PM

Answer