Random random = new Random(1334); //使用种子使数组内部的值是唯一的 var arr = newint[200]; for (int i = 0; i < arr.Length; i++) arr[i] = random.Next(0, 20); //该数组内的数据都是0~19
不使用LINQ
1 2 3 4 5 6 7 8 9 10 11 12 13 14
staticvoidNormal3(int[] arr) { Console.WriteLine("不使用LINQ"); Dictionary<int, int> dict = new(); //用来装载数组值与对应的频率,键为数组值,值为出现次数 foreach (int i in arr) { if (dict.ContainsKey(i)) //若存在,则+1 dict[i] += 1; else dict.Add(i, 1); //若不存在,则添加键值对 } foreach (int i in dict.Keys) //全部打印出来 Console.WriteLine(i + " frequency is " + dict[i]); }
12 frequency is11 4 frequency is17 5 frequency is8 9 frequency is15 6 frequency is8 13 frequency is7 0 frequency is9 3 frequency is10 1 frequency is8 18 frequency is7 14 frequency is10 2 frequency is8 15 frequency is14 16 frequency is10 8 frequency is12 10 frequency is11 17 frequency is5 11 frequency is11 7 frequency is8 19 frequency is11
staticvoidQueryExpressionLINQ3(int[] arr) { Console.WriteLine("查询表达式LINQ"); var result = from x in arr //从arr内取出所有元素并取名x group x by x into g //为x的值为x进行分组,装载到g,此时g的类型是类似于键值对形式的 selectnew { num = g.Key, count = g.Count() }; //使用匿名类来装载,num为键也就是数组的元素,count就是该组的值 foreach (var keyValuePair in result) //全部打印出来 Console.WriteLine(keyValuePair.num + " frequency is " + keyValuePair.count); }
12 frequency is11 4 frequency is17 5 frequency is8 9 frequency is15 6 frequency is8 13 frequency is7 0 frequency is9 3 frequency is10 1 frequency is8 18 frequency is7 14 frequency is10 2 frequency is8 15 frequency is14 16 frequency is10 8 frequency is12 10 frequency is11 17 frequency is5 11 frequency is11 7 frequency is8 19 frequency is11
使用LINQ(链式表达式)
1 2 3 4 5 6 7 8 9 10 11 12 13
staticvoidChainedExpressionLINQ3(int[] arr) { Console.WriteLine("链式表达式LINQ"); //对arr使用分组,分组形式为数组元素x通过数组元素x来分组,这时result为分组元素的可迭代集合, //再挑选,将分组元素g使用匿名类来装载,num为分组名(数组元素),count为该组的值,这时result为匿名类的可迭代集合 var result = arr.GroupBy(x => x) .Select(g => new { num = g.Key, count = g.Count() }); //你也可以这样写,将分组元素直接转化为Dictionary<>类型 var res = arr.GroupBy(x => x) .ToDictionary(g => g.Key, g => g.Count()); foreach (var keyValuePair in result) Console.WriteLine(keyValuePair.num + " frequency is " + keyValuePair.count); }
12 frequency is11 4 frequency is17 5 frequency is8 9 frequency is15 6 frequency is8 13 frequency is7 0 frequency is9 3 frequency is10 1 frequency is8 18 frequency is7 14 frequency is10 2 frequency is8 15 frequency is14 16 frequency is10 8 frequency is12 10 frequency is11 17 frequency is5 11 frequency is11 7 frequency is8 19 frequency is11