求助:如何将一维数组中不同的值找出来,并统计各值出现次数?
新手再次求助!多谢各位!我有一个数组,比如{1,2,3,2,3,6},当然是假设。因为事先并不知道元素值。需要统计出各元素值及出现次数,如何实现呢?请指点?
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[] testDataList = new int[] { 1, 2, 3, 2, 3, 6 ,6,1,1,3,3}; Stat1(testDataList); Console.WriteLine("************************"); Stat2(testDataList); Console.Read(); } /// <summary> /// 方法一 /// </summary> /// <param name="testDataList"></param> static void Stat1(int[] testDataList) { Dictionary<int, int> statDic = new Dictionary<int, int>(); foreach (int i in testDataList) { //还不存在于statDic中 if (!statDic.ContainsKey(i)) { statDic.Add(i, 1); } else //已经存在了,就在value中加一 { statDic[i] += 1; } } foreach (int key in statDic.Keys) { Console.WriteLine("{0} -> {1}", key.ToString(), statDic[key].ToString()); } } /// <summary> /// 方法二 /// </summary> /// <param name="testDataList"></param> static void Stat2(int[] testDataList) { List<DataT> lists = new List<DataT>(); foreach (int i in testDataList) { DataT t = new DataT(); t.ID = i; lists.Add(t); } var q = from t1 in lists group t1 by t1.ID into g select new { g.Key, Stat = g.Count(p => p.ID == g.Key) }; foreach (var q1 in q) { Console.WriteLine("{0} -> {1}", q1.Key.ToString(), q1.Stat.ToString()); } } } public class DataT { public int ID { get; set; } } }