求解集合内相同元素个数的C#解法

例如有这样一个string类型的数组:{ "A", "B", "C", "B", "A", "B", "C", "B" },求这个集合内相同元素的个数?

C#解法:

(1)通过linq解答:

         string arr={ "A", "B", "C", "B", "A", "B", "C", "B" };

         var result = from s in arr group s by s;
         foreach (var s in result)
         {
                Console.WriteLine("{0}:{1}", s.Key, s.Count());
         }

(2)通过数据结构Dictionary<type, type>求解

string arr={ "A", "B", "C", "B", "A", "B", "C", "B" };

        Dictionary<string, int> list = new Dictionary<string, int>();
            for (int i = 0; i < arr.Length; i++)
            {
                if (list.ContainsKey(arr[i]))
                {
                    list[arr[i]]++;
                }
                else
                {
                    list.Add(arr[i], 1);
                }
            }
            foreach (string item in list.Keys)
            {
                Console.WriteLine("{0}:{1}", item, list[item]);
            }

总结:经过vs2008测试通过

posted @ 2010-08-17 13:22  小麻雀  阅读(1173)  评论(0编辑  收藏  举报