0

I have a function that is given a list of strings from a database to display as options in a select filter. It handles case variants with StringComparer.InvariantCultureIgnoreCase.

public static List<string> GetMostCommonItems(List<string> values)
        {
                                           
            var filterData = values.Where(rawValue => !string.IsNullOrEmpty(rawValue))
                                   .GroupBy(item => item.ToLower())
                                   .ToDictionary(g => g.Key, g => g.GroupBy(gx => gx, StringComparer.InvariantCultureIgnoreCase).ToDictionary(gy => gy.Key, gy => gy.Count()));



            var data = filterData.Select(element => element.Value.OrderByDescending(a => a.Value).FirstOrDefault().Key).OrderBy(c => c).ToList();

            if (values.FirstOrDefault(x => string.IsNullOrEmpty(x)) != null)
            {
                data.Add(null);
            }

            return data;
        }

Now when I load the list of options it will display only lower case if there is any, if not Capital case if there is any, if not UPPER CASE.

I would like to count all lower, capital and upper case variants and only add the highest occurrence.

  • Does this answer your question? [C# Find most common strings in string array](https://stackoverflow.com/questions/39598473/c-sharp-find-most-common-strings-in-string-array) – Ryan Pattillo Jul 18 '22 at 01:03
  • Can you add an example input list and the expected result? For example, what output do you want for "One", "Two", "TWO", "three", "Three", "THREE" – tymtam Jul 18 '22 at 01:04

1 Answers1

1

Here's my solution:

List<string> values = new List<string>{
    "aaa", "aaa", "Aaa", "BBB", "BBB", "bbb"
};


var filterData = values
    .Where(rawValue => !string.IsNullOrEmpty(rawValue))
    .GroupBy(gx => gx, StringComparer.InvariantCultureIgnoreCase)
    .Select(g => new { g.Key, Best = g.GroupBy(x => x).Select( g2 => new { g2.Key, Count = g2.Count() }).OrderByDescending( x => x.Count).FirstOrDefault() });


           

foreach(var d in filterData)            
{
    Console.WriteLine($"{d.Best.Key} @ {d.Best.Count}");
}

This prints:

aaa @ 2
BBB @ 2
tymtam
  • 31,798
  • 8
  • 86
  • 126