木子屋 Dnawo's BLOG

C#统计数组所有元素出现次数

👤 dnawo 📅 2009-08-03 👁 7099 👍 0 💬 0 🔄 本站原创
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "1,2,3,4,5,2,1,9";
            string[] ids = str.Split(new char[] { ',' });

            Dictionary<string, int> dict = new Dictionary<string, int>();

            //统计
            for (int i = 0; i < ids.Length; i++)
            {
                if (dict.ContainsKey(ids[i]))
                    dict[ids[i]]++;
                else
                    dict.Add(ids[i], 1);
            }

            foreach (KeyValuePair<string, int> kvp in dict)
            {
                Console.WriteLine(kvp.Key + ":" + kvp.Value);
            }

            Console.ReadKey();
        }
    }
}

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 C#图片格式转换 下一篇 → Effective C# 原则19:选择定义和实现接口,而不是继…