利用c#二重回圈求眾數?
uj5u.com熱心網友回復:
一次回圈就能做到假定有陣列 var list = new List<int>() { 1, 2, 5, 3, 2, 4, 6, 2, 21, 45 }; 可以通過定義 Dictionary<int, int> 做,請看代碼
var numberList = new Dictionary<int, int>();
foreach (var temp in list)
{
if (numberList.ContainsKey(temp))
{
numberList[temp]++;
}
else
{
numberList[temp] = 1;
}
}
Console.WriteLine("存在的眾數");
foreach (var temp in numberList.Where(pair => pair.Value>1).Select(pair=>new {Number=pair.Key,Count=pair.Value}).OrderByDescending(temp=>temp.Count))
{
Console.WriteLine($"元素 {temp.Number} 出現次數 {temp.Count}");
}
本文代碼放在 [github](https://github.com/lindexi/lindexi_gd/tree/dd9092c538315c30f71526bc3c210d26be428f52/JekigaranekiferLaijolellecho) 可以復制全部代碼在你本地運行
uj5u.com熱心網友回復:
有道是現成函式其實作難道能逃脫回圈?自己寫用嵌套回圈更明白如何實作。轉載請註明出處,本文鏈接:https://www.uj5u.com/net/64963.html
標籤:C#
上一篇:python 爬蟲 求助 已爬取到的內容如何保存成圖片
下一篇:c#表單切換
