简体   繁体   中英

How to remove duplicates from list C#

I want get same result as got with this code to remove duplicates for text document:

 File.WriteAllLines(@"doc.txt", lines.Select(line1 => line1.Trim()).Distinct().ToArray());

Same for list with large content after loading into the list or on the stage of loading but not from processed file:

List<string> contentList = new List<string>(); 

to read content I use it this way:

for (int i = 0; i < contentList.Count; i++)
{                        
     textBox8.AppendText(contentList[i] + "\n");                        
}

and on the loading stage also inside the loop string by string:

contentList.Add(inputStr);

Desired result is avoid duplicates if I got duplicates inside:

one
two
three
four
two
five
six
three

desired result should be:

one
two
three
four    
five
six

If you have list of strings you can use Distinct() method of LINQ.

var result = contentList.Distinct();

If you have list of objects then you will need to implement custom equality comparer which will lets you to apply custom distinct rule.

Please make sure you included System.Linq namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM