How to search for a single instance of an element in int array that match a condition or return the default value in C#

3 Answers

0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 5, 8 };

            try
            {
                int n = arr.SingleOrDefault(element => element == 35);

                Console.WriteLine(n);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


/*
run:

0

*/

 



answered Feb 27, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 5, 8, 19};

            try
            {
                int n = arr.SingleOrDefault(element => element == 5);

                Console.WriteLine(n);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


/*
run:

5

*/

 



answered Feb 27, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 1, 2, 5, 8, 19};

            try
            {
                int n = arr.SingleOrDefault(element => element == 1);

                Console.WriteLine(n);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


/*
run:

Sequence contains more than one matching element

*/

 



answered Feb 27, 2017 by avibootz
...