简体   繁体   English

如何从列表C#中删除重复项

[英]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. 如果您有字符串列表,则可以使用LINQ的Distinct()方法。

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. 请确保您包括System.Linq命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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