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测试通过

  • 相关阅读:
    使用webService时,gsoap数据类型注意事项
    DB:HQL
    云:政务云
    专业词汇:电子政务(政府运作模式)
    Java-框架-Dubbo:Dubbo
    架构-Java-Netty:Netty框架
    职业-企业家:企业家
    信息服务:高考填报志愿综合参考系统
    Java-Class-FC:java.time.Duration.java
    Java-Class-@I:java.annotation.Resource.java
  • 原文地址:https://www.cnblogs.com/zwq194/p/1801411.html
Copyright © 2011-2022 走看看