Ravi Poojara
Ravi Poojara

Reputation: 9

Get count of each distinct word from array of strings

I have array of strings:

string[] arrStr = {"I am from USA","I like stackoverflow","stackoverflow always helps"};

I want to get count of each word from all the strings like

I : 2                 
stackoverflow : 2              
from : 1

I want to get this result using LINQ and only using one statement

Upvotes: 0

Views: 157

Answers (2)

ocuenca
ocuenca

Reputation: 39376

You can do that with a group by and also using SelectMany to flatten all the words first:

var result= array.SelectMany(s=>s.Split(' '))
                 .GroupBy(s=>s)
                 .Select(g=>new {Word= g.Key,Count=g.Count()});

Upvotes: 1

The One
The One

Reputation: 4696

You can do like this:

  string[] words =string.Join(" ",arrStr).Split(' ').ToArray();

        var groups =
            from w in words
            group w by w into g
                select new
                {
                 Count=g.Count(), 
                 Word=g.Key
                };

It will give you a collection of objects like:

Count: 2 Word: stackoverflow

Count: 1 Word: from

Upvotes: 1

Related Questions