我有一个“活动”类型的列表。我需要在该列表中找到最常出现的元素。例如:
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项目中,因此效率非常重要:)我认为最有效的方法是什么?
使用Linq,这很容易。
var query = activityList.GroupBy(x => x.Location)
.Select(group => new {Location = group.Key, Count = group.Count()})
.OrderByDescending(x => x.Count);
var item = query.First();
var mostfrequent = item.Location;
var mostfrequentcount = item.Count;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句