我正在尝试制作百分比计算器。我有一个数组,我想看到每个元素出现的次数,然后除以总出现次数得到一个百分比。所以我想要一个输出: * / 1 = 12% * / 2 = 15% ...
int[] n1 = { 1, 2, 3, 4, 5, 6, 1, 2, 4, 5, 6, 3, 1, 2, 5, 6 };
int c = n1.Count();
Console.WriteLine ("the total number of " + c );
Dictionary<int, int> counts = n1.GroupBy (x => x).ToDictionary (g => g.Key, g => g.Count ());
答案 0 :(得分:0)
尝试这样的事情:
int[] n1 = { 1, 2, 3, 4, 5, 6, 1, 2, 4, 5, 6, 3, 1, 2, 5, 6 };
int c = n1.Count();
var keyValue = n1.GroupBy (n => n).Select (n=> new KeyValuePair<int,string>(n.Key,((decimal)n.Count()/(decimal)c).ToString("0.0%")));
响应:
Key = 1, Value = 18.8%
Key = 2, Value = 18.8%
Key = 3, Value = 12.5%
Key = 4, Value = 12.5%
Key = 5, Value = 18.8%
Key = 6, Value = 18.8%