Retrieve Distinct Values From NotePad Elements

Viewed 80

I've a notepad file that has the following format:

at-2017@yahoo.com
at-2017@yahoo.com
at-2018@yahoo.com
at-2018@yahoo.com

I require the following distinct output:

at-2017@yahoo.com
at-2018@yahoo.com

Tried the following code but it doesn't get distinct values:

List<string> lst = new List<string>();
foreach (string line in File.ReadLines(values))
{
   line.Distinct().ToString();
   lst.Add(line);    
}

I know, this may seem stupid and guessing, missed something here.

2 Answers

Distinct() operates on a collection of elements, so you don't need to use it inside the loop.

Try following:

var lst = File.ReadLines(values).Distinct();
foreach (string line in lst)
{
    Console.WriteLine(line) ;
}

First you should read all the lines and then get the distinct lines:

var allLines = File.ReadLines(values);
var distinctLines = allLines.Distinct();
foreach(var distinctLine in distinctLines)
{
    Console.WriteLine(distinctLine);
}
Related