Use SingleOrDefault in Linq.

Total Post:45

Points:315

C#  LINQ 
 1074  View(s)
Ratings:
Rate this:
We want to use SingleOrDefault in Linq. how to use this please help me.
  1. 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();

    }

    }

    }

      Modified On Apr-11-2018 02:18:21 AM

Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.