MWU*_*ser 4 .net c# asp.net loops list
我有一个“活动”类型的列表。我需要找到该列表中出现次数最多的元素。例如:
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.
Run Code Online (Sandbox Code Playgroud)
现在我需要找到这个列表中出现次数最多的位置。例如,上例中出现次数最多的 Location 是:USA。
我试过这个:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我被卡住了,看起来效率不高。它在 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;
Run Code Online (Sandbox Code Playgroud)