-1

I'm having some issues with the following: I have a txt file with roughly two thousand names, with a bunch of duplicate entries. I'm trying to create something where it will list the amount of times a name appears. So for example: John Doe | 48 times Jane Doe | 20 times etc etc.

I found examples here on how i could count this, but i have absolutely no idea how i could have this output this to a richTextbox or other file for example.

            .Select(s => new { Key = s.Key, Count = s.Count()})
            .ToDictionary(d => d.Key, d => d.Count);```
marceltje
  • 107
  • 1
  • 9

4 Answers4

1

Data enter into the file names.txt file.

John Deo John Deo John Deo John wick John wick Testing Testing

I have made file into the project called names.txt and read him in code which are below.

string[] lines = File.ReadAllLines("../../names.txt"); 

Then grouping the names and print into the console application.

var mylines = lines.GroupBy(g => g).Select(s => new { Name = s, Count = s.Count() });
            foreach (var line in mylines)
            {
                Console.WriteLine($"{line.Name.Key} | {line.Count}");
            }  

Result#

John Deo | 11 John wick | 2 Testing | 5

Shahzad Khan
  • 432
  • 2
  • 14
0

There are many different ways to do this. If all you want is to determine the counts and how it's displayed doesn't matter then you could output the counts to a CSV file and look at it with Excel. I don't know exactly how your names are formatted in the simple example below I assume one name per line.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (var reader = new StreamReader("names.txt"))
            {
                var names = GetNames(reader).ToLookup(k => k);

                using (var writer = new StreamWriter("names.counted.csv"))
                {
                    foreach (var name in names)
                    {
                        writer.WriteLine($"{name.Key},{name.Count()}");
                    }
                }
            }

        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.ToString());
        }
    }

    static IEnumerable<string> GetNames(TextReader reader)
    {
        string line;
        while ((line = reader.ReadLine()) != null)
            yield return line;
    }
}
MikeJ
  • 1,299
  • 7
  • 10
0

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

Menachem Hornbacher
  • 2,080
  • 2
  • 24
  • 36
0

You could iterate over the results of your query and add each name/count to a StringBuilder, then output the final string to your RichTextBox:

StringBuilder sb = new StringBuilder();
foreach(var KVP in yourDictionaryVariableName)
{
    sb.AppendLine(KVP.Key + " | " + KVP.Value.ToString());
}
richTextBox1.Text = sb.ToString();
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40