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

  • 相关阅读:
    一. js高级(1)-面向对象编程
    tips01- 定位
    h5c3 part6 flex
    h5c3 part5 background and transform
    template and pagination
    h5c3 part4
    h5c3 part3
    h5c3 part2
    h5c3 part1
    学习博客
  • 原文地址:https://www.cnblogs.com/zwq194/p/1801411.html
Copyright © 2011-2022 走看看