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