有什么方法可以计算二维数组中等于 "x" 的元素吗? C#

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

pole.Count();适用于一维数组,有没有办法,如何使用二维数组?

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();
        }
    }
}

或者如何计算二维数组中的元素 == x?

您将需要 LINQ

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

它有什么作用?它遍历每个维度 d,并将出现的次数相加为最终结果 - count.

使用.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));

打印:2 Link: https://dotnetfiddle.net/c9Uluj

P.S。数组索引从 0

开始