Search code examples
c#arrayslistdictionarykeyvaluepair

Iterating through a string array and filling a dictionary type with <key, value> as word, occurenceCount --


My problem is as follows -

I am creating an array as follows(refer pic ---> https://pasteboard.co/JzJohvs.png) -

I want to count occurrence of words in this array and create an arraylist or a dictionary whichever is suitable.

My code -

    public List<Dictionary<string, int>> GetWordCount(string[] myArray)
    {
        try
        {
            var countedObj = new List<Dictionary<string, int>>();

            Array.Sort(myArray);

            var counts = myArray.GroupBy(w => w).Select(g => new { Word = g.Key, Count = g.Count() }).ToList();

            for(int index=0; index<counts.Count; index++)
            {
                var item = counts.ElementAt(index);

                var itemkey = item.Word;

                var itemvalue = item.Count;

                countedObj.Add(new Dictionary<string, int>()
                {
                    
                });
            }

            return countedObj;
        }
        catch(Exception exp)
        {
            throw exp.InnerException;
        }
    }

What I need is to create a dictionary list such as

life, 3 inherent, 2 useful, 1, educated, 5, lgitimate, 2 and so on......

basically key value pair type. I'm sure you get what I basically intend to achieve. Something that I can iterate and process later on as per my need. How can I do that? What type of iteration is required? some relevant code suggestions here.


Solution

  • You can group by the words, select the count of each group (which you're already doing), and then turn that into a dictionary with the word as the key and the count as the value:

    Dictionary<string, int> wordCounts = myArray
        .GroupBy(word => word)
        .ToDictionary(group => group.Key, group => group.Count());
    

    So the method could be re-written as:

    public static Dictionary<string, int> GetWordCount(string[] myArray)
    {
        return myArray?
            .GroupBy(word => word)
            .ToDictionary(group => group.Key, group => group.Count());
    }
    

    And then sample usage might be:

    var words = new[] {"one", "two", "two", "three", "three", "three"};
    
    foreach (var item in GetWordCount(words))
    {
        Console.WriteLine($"{item.Key} = {item.Value}");
    }
    

    Output

    one = 1
    two = 2
    three = 3