Home > DeveloperSection > Forums > Use SingleOrDefault in Linq.
Norman Reedus
Norman Reedus

Total Post:45

Points:315
Posted on    March-18-2016 11:16 PM

 LINQ C#  LINQ 
Ratings:


 1 Reply(s)
 244  View(s)
Rate this:
We want to use SingleOrDefault in Linq. how to use this please help me.


aditya kumar Patel

Total Post:250

Points:1782
Posted on    March-18-2016 11:19 PM

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

}

}

}


Don't want to miss updates? Please click the below button!

Follow MindStick