How to search for a single instance of an element in int array that match a condition with 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, 33, 4, 5 };

            try
            {
                int n = arr.Single(element => element > 10);
                Console.WriteLine(n);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


/*
run:

33

*/

 



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, 33, 4, 5, 15};

            try
            {
                int n = arr.Single(element => element > 10);
                Console.WriteLine(n);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


/*
run:

Sequence contains more than one matching element

*/

 



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 = { 13 };

            try
            {
                int n = arr.Single();

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


/*
run:

13

*/

 



answered Feb 27, 2017 by avibootz
...