首页 > 解决方案 > 删除文本文件中的重复记录

问题描述

下面是检索数据库数据并存储在 DataTable 中并将写入文本文件的源代码。因此,我设法将记录保存在文本文件中,但存在重复数据,如下所示。

loggo2.txt

122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03

我想要的是这个输出:

122222 08-0943-03
123333 08-0943-03

但是,我想在写入文本文件之前删除重复项,以便下次我可以在没有任何重复项的情况下存储在数据库中,请帮助

foreach (DataRow row1 in dt.Rows)
{
  if (row["Material"].ToString().ToLower().Contains(row1["Material"].ToString().ToLower()))
  {
    //// if match, then write the result
    string filename1 = "loggo2.txt";
    filename1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename1);
    using (StreamWriter w = File.AppendText(filename1))
    {
        var line = String.Format("{0} {1}", row1["Component"], row1["Material"]);
        w.WriteLine(line);
    }
  }
}

标签: c#duplicates

解决方案


或者,您可以通过 linq 重新排列文件。

string path = @"C:\sampleText.txt";
string[] allText = File.ReadAllLines(path, Encoding.UTF8).Where(c => c != null && c != "").Select(item => item + Environment.NewLine).Distinct().ToArray();

File.WriteAllLines(path, allText);

输入 :

122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03
122222 08-0943-03
123333 08-0943-03

输出 :

122222 08-0943-03

123333 08-0943-03

推荐阅读