zoukankan      html  css  js  c++  java
  • 求解集合内相同元素个数的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测试通过

  • 相关阅读:
    每天一个linux命令
    Python 面向对象-下篇
    Python 面向对象-上篇
    何时会发生隐式类型转换
    C++类型检查
    无符号保留原则
    bool类型为什么可以当做int
    在类的外部定义成员函数注意形式
    局部类
    命名规范
  • 原文地址:https://www.cnblogs.com/zwq194/p/1801411.html
Copyright © 2011-2022 走看看