有这样几个3、400M的文本,结构如下:
产品名称 单价 数量 总价xxx       x     n    x……
后面很多,且各文本中相互间产品名称有重复的,重复就要对数量和总价进行相加,
因为每个文本的数据量太大没法读入内存处理,请高手指点。
还有,不能用数据库

解决方案 »

  1.   


    不算大,用文件流分段打开处理就可以了。别一次性读入内存。放数据库吧,比如access也行
      

  2.   

    我想了想,这样做:一、准备保存结果用的数据结构。总价=单价*数量,所以为了效率,最后再自动计算
    List<Product> table = new List<Product>();class Product
    {
        public string name;
        public decimal price;
        public int count;    private Product()
        {
        }    public Product(string name, decimal price, int count)
        {
            this.name = name;
            this.price = price;
            this.count = count;
        }
    }
    二、读取数据,一次从文本读一行。
    using (StreamReader sr = new StreamReader(@"file.txt"))
    {
        string row;
        while (sr.Peek() >= 0)
        {
            row = sr.ReadLine();
            string[] cols = row.Split(' ');
                        
            string name = cols[0];
            decimal price = decimal.Parse(cols[1]);
            int count = int.Parse(cols[2]);        table.Add(new Product(name, price, count));
        }
    }三、生成结果var result = table.GroupBy(k => k.name)
        .Select(g => g.Select(p => new
        {
            name = g.Key,
            price = p.price,
            count = g.Sum(e => e.count),
            total = p.price * g.Sum(e => e.count)
        })).SelectMany(r => r);Console.WriteLine("产品名称    单价    数量      总价");
    foreach (var p in result)
        Console.WriteLine("{0}    {1}    {2}      {3}", p.name, p.price, p.count, p.total);如果嫌速度慢,可以引入多线程和并行LINQ。
      

  3.   

    最重要的是List<Product> table = new List<Product>();装不下合并的结果
    没处理完就显示内存溢出了
      

  4.   

    数据量那么大,List<>的膨胀速度确实会很惊人。不行就自己简单地分一下页?比如每读取5K行就汇总一次,把汇总结果存入一个中间文件,比如temp1.txt。然后再读下一个5K行,依此循环。最后再对temp1.txt、temp2.txt这些中间文件进行二次汇总。这么大数据量,不用数据库,真的很麻烦。
      

  5.   

    "最重要的是List<Product> table = new List<Product>();装不下合并的结果,没处理完就显示内存溢出了"
    LZ,分两个步骤:
    1、用HashTable,哈希表的空间伸缩范围要大。
    2、遍历文本同时,进行计算处理,不能先装,在合并,这样消耗内存太大了!如果哈希表都不能解决你的问题,建议先把文本导入到数据库中,在进行处理,毕竟数据库伸缩的空间比内存要大多了。