2

I'm trying to sort a list alphabetically, then once the list is sorted, print the name of any element in the list which occurred more than once.

Most google searches only address comparing separate lists. I know you can compare strings, and that list elements (in this case are strings), but I'm not sure how to compare these strings since they're in the list.

using System;
using System.Collections.Generic;

namespace Challenge5alphabeticalOrderSorting
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            List<string> fruit = new List<string>()
            {
                "apple",
                "mango",
                "mango",
                "orange",
                "blueberry",
                "blueberry"
            };

            fruit.Sort();
            foreach (string f in fruit)
                Console.WriteLine(f);
        }
    }
}
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
jkuehlin
  • 137
  • 8

1 Answers1

3

The code below prints the duplicated names, as OP wants (not the count or something else), using GroupBy, Where and Count methods

print the name of any element in the list which occurred more than once.

var groups = fruit.GroupBy(f => f).Where(g => g.Count() > 1);
foreach (var group in groups)
    Console.WriteLine(group.Key);
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66