Reputation: 1
I am using C# to read a csv file and spit all the words in new lines. Then I want to count how many times each word in that file got repeated in the list. The output that I get is not counting the words. please see the below information
csv file content: She is nice he can be nice oh wow this is great
This is the code :
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = File.ReadAllLines("Try3.csv");
foreach (string line in File.ReadAllLines("Try3.csv"))
{
string[] parts = line.Split(' ');
foreach (string part in parts)
{
var q = list.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.OrderByDescending(x=>x.Count);
foreach (var x in q){
Console.WriteLine("{0}",part+" Count:"+ x.Count);
}
}
}
}
}
This is the output I got:
[]
Any idea please?
Upvotes: 0
Views: 1307
Reputation: 32266
Try this
var results = File.ReadLines("Try3.cvs")
.SelectMany(line => line.Split(' '))
.GrooupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());
First using File.ReadLines
will mean you only read in one line at a time instead of loading the entire file into memory before processing. This can be helpful if the file size is large. Then it's just a simple matter of splitting the lines into words then grouping on those words to create a dictionary that will have the words at the key and the number of times it showed up in the file as the value.
To get the results in order by the count you could opt to do the following instead.
var results = File.ReadLines("Try3.cvs")
.SelectMany(line => line.Split(' '))
.GrooupBy(word => word)
.OrderByDescending(g => g.Count())
.Select(g => new { Word = g.Key, Count = g.Count() })
.ToList();
Upvotes: 1