0

I'm just wondering what's the simplest way to find the same values? I am just the beginner, so I'm looking for the simplest way, without any vectors and etc.. For example, I need to sort Streets:

  • 1street

  • 2street

  • 1street

  • 3street

and the answer must be that "1street" is the most commonly named here.

Andrius
  • 21
  • 2
  • 5

1 Answers1

0

Assuming you have a List<string> that contains your items:

List<string> myList = PopulateList(...);  // fill the list with names

If you just want to sort the list, you can use List.Sort:

myList.Sort();

You could then go through the list with a loop to count up the duplicates and determine which is most frequent.

Or, you can group the items and then sort the grouping by count, descending, and take the first item.

var mostCommon = 
    myList.GroupBy(x => x)
          .OrderByDescending(g => g.Count())
          .First();

And then mostCommon.Key will tell you the most common item, and mostCommon.Count() will tell you how many items there are.

Or, if you wanted a list of {name, count}, ordered by count:

var groupedAndSorted =
    myList.GroupBy(x => x)
          .Select(x => new {Key=x.Key, Count=x.Count()})
          .OrderByDescending(x => x.Count)
          .ToList();
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351