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

4
我有一个“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项目中,因此效率非常重要。您认为最有效的方法是什么?


也可以在这里查看:http://stackoverflow.com/questions/17180139/find-max-count-of-a-list-of-custom-types - Kavindu Dodanduwa
3个回答

5
使用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;

0
activityList.GroupBy(a => a.Location)
            .OrderByDescending(g => g.Count())
            .First().Key;

0

我曾经遇到过类似的问题,我使用了一个 字典

Dictionary<Location, int>  LocationCounter; 
. . .
public void CountLocations(Location thisPlace) {
    if (!LocationCounter(thisPlace)
        LocationCounter.Add(thisPlace, 1);
    else 
        LocationCounter[thisPlace]++;
}

这里是一个关于按字典值排序的SO链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接