简体   繁体   中英

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[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. I am thinking of something like Map map = new HashMap();

You can use the GroupBy and ToDictionary extension methods found in System.Linq to perform the task:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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