c# - 删除文本文件中的重复记录
问题描述
下面是检索数据库数据并存储在 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);
}
}
}
解决方案
或者,您可以通过 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
推荐阅读
- jupyter-notebook - Jupyter 实验室分拣
- angular - Angular CRUD Delete 需要在 GetAll 中定义的 Suscribe 中进行订阅
- javascript - React 将数据从前端传递到后端节点
- python - 从变量访问函数是否更高效?
- controller - Alicat SerialTerminal 无符号设定点
- c++ - 什么样的数据分布可以使一个数字出现在不同范围内的频率发生很大变化?
- python - ffmpeg VS opencv有什么不同的视频分割?
- reactjs - NextJS 动态 SEO 元标记在 Facebook、Twitter 等社交网站上给出 500 个内部错误
- react-native - 世博会上是否有对讲机的替代品反应原生?
- relative-path - bash 中是否有用于“..”的 QMake 模拟?