[英]Group list of strings by most common case variant
我有一個函數,它給出了數據庫中的字符串列表,以在選擇過濾器中顯示為選項。 它使用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.