简体   繁体   English

按最常见的案例变体对字符串列表进行分组

[英]Group list of strings by most common case variant

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.它使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM