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

时间:2014-06-09 03:13:37

标签: c# arrays string

我有用户名列表(字符串)。每个名字 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"

现在我需要计算总共有多少技能,每项技能有多少人。 所以我认为它将包含以下步骤:

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", ... };

我们可以通过以下方式检查频率:

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

3。我不知道如何将计数数字粘贴到每个技能上,然后我们可以显示它。 我在想像Map map = new HashMap();

1 个答案:

答案 0 :(得分:1)

您可以使用System.Linq中的GroupByToDictionary扩展程序来执行任务:

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"];