0

I have some code that removes duplicate lines from a text file, it then outputs the result (text with no duplicates) to a file. How could I also declare this output as a string as well?

private static void RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
    var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);

    File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
}

2 Answers 2

5

You could have the method return a string value:

private static string RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
    var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
    var result = readLines.Distinct().ToArray();
    File.WriteAllLines(destinationFilePath, result, Encoding.Default);
    return string.Join(Environment.NewLine, result);
}

and then:

string result = RemoveDuplicate("source.txt", "dest.txt");
Sign up to request clarification or add additional context in comments.

4 Comments

Isnt result an array? than a string
@BrokenGlass and @Adithya Surampudi, yes, I have just realized that and fixed my answer.
If I wanted to use this string in another method how could I declare it?
@James, I showed in my answer: string result = RemoveDuplicate("source.txt", "dest.txt");.
0

String should be returned, not string array so,use String.join, you can use your own delimiter to seperate lines, i used comma, you could use a new line.

private static string RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
var result = readLines.Distinct().ToArray();
string resultString =  String.Join(",",ids);
File.WriteAllLines(destinationFilePath, result, Encoding.Default);
return resultString;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.