4

I have a list of type "Activity". And I need to find the most occurring element in that list. For example:

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.

Now I need to find the most occurring Location in this list. For example, the most occurring Location in the example above would be: USA.

I tried this:

            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
                    }
                }
            }

But I got stuck and looks like it's not very efficient. It's in a ASP.NET web project, so efficiency is very important I think :) What is the most efficient way to get this done?

MWUser
  • 267
  • 1
  • 7
  • 18

3 Answers3

5

This is trivially easy with 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;
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
0
activityList.GroupBy(a => a.Location)
            .OrderByDescending(g => g.Count())
            .First().Key;
Victor Hurdugaci
  • 28,177
  • 5
  • 87
  • 103
0

I've had to do something similar and I used a 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

Community
  • 1
  • 1
radarbob
  • 4,964
  • 2
  • 23
  • 36