简体   繁体   English

字符串数组中的字符串计数频率

[英]Count frequency of string in string array

I have list of usernames (string). 我有用户名列表(字符串)。 Each name cn[i] will have several skills attached to it: 每个名称cn [i]都会具有几个技能:

cn[0] has: "text1, text2, text3"
cn[1] has: "text2, text4, text6"
cn[2] has: "text6, text8"
cn[2] has: "text11, text8, text1, text4, text2"

etc. 等等

Now I need to count how many skills in total and each skill how many people have. 现在,我需要计算总共有多少技能,每项技能有多少人。 So I think it will contain following steps: 所以我认为它将包含以下步骤:

1. add text1, text2, ... to an array (I don't know how to get each string and get rid of the comma "'")
2. suppose we have 

    string[] stringArray = { "text1", "text2", "text3", "text4", "text6", ... };

we can check the frequency by: 我们可以通过以下方式检查频率:

foreach (string x in stringArray)
{
    if (x.Contains(stringToCheck))
    {
        // increase the number of count
    }
}

3. I don't know how to stick that count number to each skill then later we can display it. 3.我不知道如何将计数数字粘贴到每个技能上,然后我们可以显示它。 I am thinking of something like Map map = new HashMap(); 我在想像Map map = new HashMap();

You can use the GroupBy and ToDictionary extension methods found in System.Linq to perform the task: 您可以使用System.LinqGroupByToDictionary扩展方法来执行任务:

using System.Linq;

var frequency = cn
    .SelectMany(u => u.Split(new string[] { ", " }, StringSplitOptions.None))
    .GroupBy(s => s)
    .ToDictionary(g => g.Key, g => g.Count());

var numberOfSkills = frequency.Count;

var numberOfUsersWithSkillOne = frequency["SkillOne"];

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

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