C#:获取列表中最常出现的元素?

时间:2015-02-23 03:08:16

标签: c# asp.net .net list loops

我有一个“活动”类型的列表。我需要在该列表中找到最常出现的元素。例如:

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.

现在我需要在此列表中找到最常出现的位置。例如,上例中最常出现的位置是: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
                    }
                }
            }

但我卡住了,看起来效率不高。它位于ASP.NET Web项目中,因此我认为效率非常重要:)完成此任务的最有效方法是什么?

3 个答案:

答案 0 :(得分:2)

对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;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我必须做类似的事情而且我使用Dictionary

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

Here is a SO link about sorting by dictionary value