对百万级txt文件的数据,进行查重处理

  1. 需求1: 比对A、B两个文件,其中A文件是B文件的一部分,找出A、B文件的差集。

  2. 使用hashset 分别保存要比对的数据,然后求差集,主要代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CompareFile
{
    class Program
    {

        static void Main(string[] args)
        {
   

            HashSet<string> fullLst = new HashSet<string>();//bao

            using (StreamReader sr = new StreamReader("full.txt"))
            {

                string line = "";
                string last_data = "";
                int idx = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    idx++;
                    if (line != last_data)
                        fullLst.Add(line);
                     last_data = line;

                    //或者使用另外一种方式
                    //if (!fullLst.Contains(line))
                    //    fullLst.Add(line);

                    if (idx % 10000 == 0)
                        Console.WriteLine(idx);
                }

            }
            Console.WriteLine("已完成读取full.txt");
            HashSet<string> compareLst = new HashSet<string>();
            using (StreamReader sr = new StreamReader("compare.txt"))
            {
                string line = "";
                int lineID = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    lineID++;
                    compareLst.Add(line);
                    if (lineID % 10000 == 0)
                        Console.WriteLine(lineID);
                }
            }
            Console.WriteLine("读取compare.txt已完成");
            fullLst.ExceptWith(compareLst);

            Console.WriteLine("full.txt 与 compare.txt 差集 count: " + fullLst.Count);

            //将差集文件导出
            using (StreamWriter sr = new StreamWriter("diff.txt"))
            {
                foreach (string item in fullLst)
                    sr.WriteLine(item);
            }
            Console.WriteLine("比对结果已导出");

            Console.ReadLine();

        }
    }
}

代码demo下载地址
. PS:
最初,考虑把读到的数据放入List中,去重使用List.constains()判断,如果包含在不添加,否则添加的到 list中。
编译代码,发现运行的非常慢,
代码逻辑比较简单,就改用string last 变量保存读到的数据,本次读到的数据保存到last,下一次读取时,如果与last不同在添加,并更新last值。

编译运行很快。

结论:list.constains()在数据量很大时,检索是否包含某个值,是很慢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值