我有一个“Activity”类型的列表,需要找到出现最多的元素。例如:
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项目中,因此效率非常重要。您认为最有效的方法是什么?