Is there any way to count elements that are equal to "x" in 2D aray; C#

98 views Asked by At

pole.Count(); works for 1D array, is there way, how to do that with 2D array?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4___TEST
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] pole = new string[3];
            int[,] array = new int[2, 2];
            array[1, 1] = 1;
            array[1, 2] = 2;
            array[2, 1] = 2;
            array[2, 2] = 1;
            pole[1] = (Console.ReadLine());
            pole[2] = (Console.ReadLine());
            Console.Write("Zadej p: ");
            string p = (Console.ReadLine());
            int count = pole.Count(x => x == p)
            Console.WriteLine("{0} se vyskytuje v poli {1}-krát", p, count);
                Console.ReadLine();
        }
    }
}

Or how can I count elements == x in 2D array?

2

There are 2 answers

0
FoggyFinder On BEST ANSWER

Use .OfType():

    int[,] array = new int[2, 2];
    array[0, 0] = 1;
    array[0, 1] = 2;
    array[1, 0] = 2;
    array[1, 1] = 1;

    int x = 2;
    Console.WriteLine(array.OfType<int>().Count(y => y == x));

Print: 2 Link: https://dotnetfiddle.net/c9Uluj

P.S. array indexing starts at 0

0
user35443 On

You are going to need LINQ

int p = Int32.Parse(Console.ReadLine());
int count = array.Cast<int>().Count(d => d == p);

Whaat does it do? It goes through every dimension d, and sums the number of occurrences into a final result - count.