gpt4 book ai didi

C#:获取列表中出现次数最多的元素?

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:11 29 4
gpt4 key购买 nike

<分区>

我有一个“事件”类型的列表。我需要找到该列表中出现次数最多的元素。例如:

Activity a = new Activity();
a.Location = "USA";

Activity b = new Activity();
b.Location = "Sri Lanka";

Activity b = new Activity();
b.Location = "USA";

List<Activity> activityList = new List<Activity>();
activityList.add(a);
//......adding the rest of the objects as well.

现在我需要在此列表中找到出现次数最多的位置。例如,上例中出现次数最多的位置是:美国。

我试过这个:

            String currentLocation = "";
String mostOccurring = "";
int currentCount = 0;
int highest = 0;

for (int i = 0; i < activityList.Count; i++)
{
currentLocation = activityList[i].Location;

foreach (Activity activity in activityList)
{
if (activity.Location.Equals(currentLocation))
{
currentCount++;
highest = currentCount;
//compare the highest count
}
}
}

但是我卡住了,看起来效率不是很高。它在 ASP.NET web 项目中,所以我认为效率非常重要 :) 完成这项工作的最有效方法是什么?

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com