【问题标题】:Is there any way to count elements that are equal to "x" in 2D aray; C#有没有办法计算二维数组中等于“x”的元素? C#
【发布时间】:2015-06-07 16:52:29
【问题描述】:

极点.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?

【问题讨论】:

    标签: c# arrays console


    【解决方案1】:

    使用 .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 链接:https://dotnetfiddle.net/c9Uluj

    附:数组索引从 0 开始

    【讨论】:

      【解决方案2】:

      你将需要 LINQ

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

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

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多