Click here to Skip to main content
14,937,188 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey Guys I have Problem I have a textbox who will have sometimes same lines now I need to count them and show the number in joined line with the text

What I have tried:

<pre>  private void textBox1_TextChanged(object sender, EventArgs e)
            string[] iste =textBox1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Distinct().ToArray();
            textBox1.Text = string.Join("\r\n", iste);

in this code it will join the lines and I am able to see just one line but I need a count of lines and if I have some number in that line to count that also
for example:
1.Earth 2

Expected :

1.Earth x2 4
Updated 27-Mar-21 13:15pm
Gerry Schmitz 26-Mar-21 14:50pm
Use a Dictionary<string,int>; the string is the word or phrase, the int is the "count".
BillWoodruff 27-Mar-21 18:14pm
Where does the data (lines) come from ? Do you have any control over its format ?
Kleo Rogers 27-Mar-21 18:32pm
They are coming from buttons so yes I have
BillWoodruff 27-Mar-21 18:36pm
see reply below

1 solution

For every possible variation in line format, you have to create a parsing strategy; so, anything you can do to control/simplify/regularize the format is valuable. Consider:
private char[] lnsplitchars = new char[] { '.', ' '};

// note absence of error checking 'real-world code' should have !

private void btnParseLines_Click(object sender, EventArgs e)
    foreach (string line in textBox1.Lines)
        string[] lnsplit = line.Split(splitchars, StringSplitOptions.RemoveEmptyEntries);

        int id = Int32.Parse(lnsplit[0]);

        string text = lnsplit[1];

        int ndups = 0;

        if (lnsplit.Length == 3)
            ndups = Int32.Parse(lnsplit[2]);
        // process line data
The real work begins with you formulating a clear strategy on transforming the parsed lines: you attempt that, and show your code.

Perhaps you will need to create an intermediate data structure ... like an Array of Arrays ... to hold the parsed line data; and/or use Linq 'GroupBy to organize duplicates.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900