按最常见的大小写变体对字符串列表进行分组



我有一个函数,从数据库中给出字符串列表,在选择过滤器中显示为选项。它使用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;
}

现在,当我加载选项列表时,如果有的话,它只会显示小写字母,

我想计算所有小写、大写和大写的变体,只添加出现次数最多的。

我的解决方案是:

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}");
}

这个打印:

aaa @ 2
BBB @ 2