How to use Array.TrueForAll() method to determine whether all array elements match a condition in C#

3 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] arr = new String[] { "hhh10", "ccc100", "bbb1000", "ggg10000",
                                          "eee100000", "aaa100000", "ddd333" };

            if (Array.TrueForAll(arr, EndsWithInteger))
                Console.WriteLine("All elements end with integer");
            else
                Console.WriteLine("Not all elements end with an integer");

        }
        private static bool EndsWithInteger(String value)
        {
            int s;
            return Int32.TryParse(value.Substring(value.Length - 1), out s);
        }
    }
}


/*
run:
    
All elements end with integer
   
*/

 



answered May 1, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] arr = new String[] { "hhh", "ccc100", "bbb1000", "ggg10000", "eee100000" };

            if (Array.TrueForAll(arr, EndsWithInteger))
                Console.WriteLine("All elements end with integer");
            else
                Console.WriteLine("Not all elements end with an integer");

        }
        private static bool EndsWithInteger(String value)
        {
            int s;
            return Int32.TryParse(value.Substring(value.Length - 1), out s);
        }
    }
}


/*
run:
    
Not all elements end with an integer
   
*/

 



answered May 1, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] arr = new String[] { "hhh12345", "ccc100", "bbb1000", "ggg10000" };

            if (Array.TrueForAll(arr, value => {
                int s;
                return Int32.TryParse(value.Substring(value.Length - 1), out s);
            }
               ))
                Console.WriteLine("All elements end with integer");
            else
                Console.WriteLine("Not all elements end with an integer");
        }
        private static bool EndsWithInteger(String value)
        {
            int s;
            return Int32.TryParse(value.Substring(value.Length - 1), out s);
        }
    }
}


/*
run:
    
All elements end with integer
   
*/

 



answered May 1, 2016 by avibootz
...