从字符串列表中获取唯一项

tim*_*ord 1 .net c#

我有一个非常简单的文本文件解析应用程序,它搜索电子邮件地址,如果找到则添加到列表中.

目前列表中有重复的电子邮件地址,我正在寻找一种快速修改列表的方法,只包含不同的值 - 而不是逐个迭代它们:)

这是代码 -

var emailLines = new List<string>();
using (var stream = new StreamReader(@"C:\textFileName.txt"))
{
    while (!stream.EndOfStream)
    {
        var currentLine = stream.ReadLine();

        if (!string.IsNullOrEmpty(currentLine) && currentLine.StartsWith("Email: "))
        {
            emailLines.Add(currentLine);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Nul*_*ion 7

如果您只需要独特的商品,则可以使用添加商品HashSet而不是商品List.请注意,HashSets没有隐含的顺序.如果您需要订购套装,则可以使用SortedSet.

var emailLines = new HashSet<string>();
Run Code Online (Sandbox Code Playgroud)

然后就没有重复了.


要删除a中的重复项List,您可以使用IEnumerable.Distinct():

IEnumerable<string> distinctEmails = emailLines.Distinct();
Run Code Online (Sandbox Code Playgroud)