Skip to main content
 首页 » 编程设计

c#之检查是否在文本文件中找到项目

2024年02月20日13telwanggs

如何检查文本文件是否包含列表框中的项目。停止保存重复项。我不确定我要添加什么。这是在按钮单击事件上调用的。例如,如果找到重复项,我可以显示 MessageBox.Show ("duplicate error");

 using (StreamWriter writer = new StreamWriter("test.txt", true)) 
        { 
            foreach (object item in listBox2.Items) 
            { 
                writer.WriteLine(item.ToString()); 
            } 
        }     

请您参考如下方法:

在写入“test.txt”之前,枚举其内容:

var fileLines = File.ReadAllLines("test.txt"); 
List<string> fileItems = new List<string>(fileLines); 

然后在你写每一项之前,检查列表是否包含它:

using (StreamWriter writer = new StreamWriter("test.txt", true)) 
{ 
    foreach (object item in listBox2.Items) 
    { 
        if (fileItems.Contains(item)) 
            // Do something, break, etc. 
        else 
            writer.WriteLine(item.ToString()); 
    } 
} 

编辑:

根据建议,您可以使用 HashSet 而不是 List 来提高性能,因为它只能包含唯一值。

另一个改进可能是在向文件写入任何内容之前检查是否存在任何重复项。我已经在下面的 LINQ 语句示例中完成了该操作:

var fileLines = File.ReadAllLines("test.txt"); 
HashSet<string> fileItems = new HashSet<string>(fileLines); 
 
using (StreamWriter writer = new StreamWriter("test.txt", true)) 
{ 
    bool duplicateFound = fileItems.Any(fi => listBox1.Items.Cast<string>().Any(i => i == fi)); 
 
    if (duplicateFound) 
        MessageBox.Show("Duplicate items found."); 
    else 
        foreach (object item in listBox1.Items) 
            writer.WriteLine(item.ToString()); 
} 

编辑 2:

正如@Servy 所建议的,列表框可​​能包含重复项,这一点也应予以考虑。此外,我的 HashSet 实现低于标准。因此,在第三个示例中,我首先检查列表框是否包含重复项,然后检查文件中是否已存在任何列表框项。 HashSet 的使用也更高效,因为我没有迭代它。

var fileLines = File.ReadAllLines("test.txt"); 
HashSet<string> fileItems = new HashSet<string>(fileLines); 
List<string> duplicateListboxItems = listBox1.Items.Cast<string>().GroupBy(l => l).Where(g => g.Count() > 1).Select(g => g.Key).ToList(); 
if (duplicateListboxItems.Count > 0) 
{ 
    MessageBox.Show("The listbox contains duplicate entries."); 
    return; 
} 
 
bool duplicateFound = false; 
List<string> outputItems = new List<string>(); 
foreach (string item in listBox1.Items) 
{ 
    if (fileItems.Contains(item)) 
    { 
        MessageBox.Show(String.Format("The file has a duplicate: {0}", item)); 
        duplicateFound = true; 
        break; 
    } 
    outputItems.Add(item); 
} 
 
if (duplicateFound) 
    return; 
 
using (StreamWriter writer = new StreamWriter("test.txt", true)) 
{ 
    foreach (string s in outputItems) 
        writer.WriteLine(s); 
}