USE SINGLEORDEFAULT IN LINQ.

Norman Reedus

Total Post:45

Points:315
Posted by  Norman Reedus
C#  LINQ 
 526  View(s)
Ratings:
Rate this:
We want to use SingleOrDefault in Linq. how to use this please help me.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: Use SingleOrDefault in Linq.

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

    }

    }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!