Assumption:
Lets say we already have each line of the text file in an List<string>
object we will call names
and that each line in the text file represents a whole name spelled correctly.
Grouping/Printing the data:
Using LINQ we can group these values by themselves (similar to SQL) and then convert the IGrouping
results into the objects we want to use later in our application. For example:
var totals = names.GroupBy(x => x)
.Select(group => new { Name = group.Key, Count = group.Count() });
foreach ( var total in totals )
{
Console.WriteLine($"{total.Name} | {total.Count} times");
}
Another option would be to use your existing code and just print out the values of the dictionary
var totals = names
.Select(s => new { Key = s.Key, Count = s.Count()})
.ToDictionary(d => d.Key, d => d.Count);
foreach ( var kvp in totals )
{
Console.WriteLine($"{kvp.Key} | {kvp.Value} times");
}
Saving/Displaying the data:
If you want to do something other then print to console you could simply manipulate the data into the value you want. For example if you want to save it to another file:
var csvContent = totals
.Select(total => $"{total.Name},${total.Count} times")
.ToArray();
File.WriteAllLines(filePath, csvContent);
Or you could create a string (e.g. in above: String.Join("\n", csvContent)
) and update a RichTextBox like so