Sijo K.S
Sijo K.S

Reputation: 21

How Can I Remove Duplicate Lines From a textBox in C#?

I have one text box the value is like that below

1
2
3
1
3

I tried:

textBox1.Text = string.Join("\r\n", **textBox1.Lines**.Distinct());

textBox1.Lines is not supporting to my program

Upvotes: 0

Views: 1859

Answers (4)

Salah Akbari
Salah Akbari

Reputation: 39956

Add this to using directives at top of page:

using System.Linq;

Then simply use like so:

textBox1.Text = string.Join(Environment.NewLine, textBox1.Lines.Distinct());

Upvotes: 2

Graffito
Graffito

Reputation: 1718

string[] distinctLines = theText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Distinct().ToArray();
textBox1.Text = string.Join("\r\n", distinctLines);

Upvotes: 1

imlokesh
imlokesh

Reputation: 2729

Even though the code you posted should work, here's a different approach.

textBox1.Text = string.Join(Environment.NewLine, textBox1.Text.Split(new[] {Environment.NewLine}, StringSplitOptions.None).Distinct());

Basically, you can split the text into lines yourself since you mention problems with Lines.

Upvotes: 0

walruz
walruz

Reputation: 1329

What do you think about that:

        string x = "1\r\n2\r\n1\r\n";

        string[] lines = x.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        var cmd = (from i in lines select i);
        string[] result = cmd.Distinct().ToArray();

        x = string.Join("\r\n", result);

Upvotes: 1

Related Questions