how to delete same lines in file .txt but keep one of them using c# ?
Asked
Active
Viewed 621 times
-1
-
Restate your question please, I wasn't able to understand it >_< sorry. – Warty May 24 '10 at 00:08
-
example I have 5 lines in text file three of them is "he is going to school" I want to delete two and keep one of them but the lines distributed in text like : It is a cat he is going to school I will take my book he is going to school he is going to school – kartal May 24 '10 at 00:12
-
Sounds like a dedupe? How do you know which one of the lines you want to keep? Do you just keep the first instance? – Phil Gan May 25 '10 at 09:17
3 Answers
10
Read line by line. Add the line to a HashSet, and Add returns true, print the line to the output.

Matthew Flaschen
- 278,309
- 50
- 514
- 539
0
There are many ways. One could be to use some version of a Set. Look at C# Set collection? for this.
If all the same lines are after one another, you could just iterate through and see if the line matches the last line. If it does, discard it.

Community
- 1
- 1

Christian Neverdal
- 5,655
- 6
- 38
- 93
0
Your code would look something like this:
- For each line in the input file.
- If the current line is not the same as the previous line, write it to the output file.
- Set the current line equal to the previous line.
This assumes that duplicate lines are adjacent. If they are not adjacent, you will have to sort the file first.

Turtle
- 1,320
- 10
- 11