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

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 | 引用: 0 | 查看次数: 6348
发表评论
登录后再发表评论!