Ler*_*ins 9 c# arraylist icomparable
我正在为特定值清理5个文件.我不期待任何不同的价值观,但因为这是出于我自己的教育目的,我希望应用程序可以计算,比较和打印最受欢迎的价值.
例如:
ArrayList arrName = new ArrayList();
arrName.Add("BOB")
arrName.Add("JOHN")
arrName.Add("TOM")
arrName.Add("TOM")
arrName.Add("TOM")
Run Code Online (Sandbox Code Playgroud)
我想要的结果是TOM,但作为一个新手,我真的不知道如何前进.
任何想法,建议或例子都非常感谢.谢谢.
您可以使用字典(.NET 2.0+)来保存每个值的重复计数:
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (string name in arrName) {
int count;
if (counts.TryGetValue(name, out count)) {
counts[name] = count + 1;
} else {
counts.Add(name, 1);
}
}
// and then look for the most popular value:
string mostPopular;
int max = 0;
foreach (string name in counts.Keys) {
int count = counts[name];
if (count > max) {
mostPopular = name;
max = count;
}
}
// print it
Console.Write("Most popular value: {0}", mostPopular);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 C# 3.0 (.NET 3.5 +),则使用:
var mostPopular = (from name in arrName.Cast<string>()
group name by name into g
orderby g.Count() descending
select g.Key).FirstOrDefault();
Console.Write("Most popular value: {0}", mostPopular ?? "None");
Run Code Online (Sandbox Code Playgroud)