2

我必须比较可能包含超过 100000 个条目的 csv 文件中的条目,并找到对并将它们存储在另一个文件中。比较必须检查两列或多列中的值,例如:

狗 5

猫 7

老鼠 5

狗 3

狗 5

在这个例子中,我必须选择对 {Dogs, 5} 并忽略其余的。你会建议什么方法?

像往常一样感谢

4

2 回答 2

2

Tuple如果您的架构真的如此简单,则可以使用and用最少的代码来完成HashSet<T>

无论如何,基本策略是创建一个数据结构来跟踪您所看到的并使用它来确定输出什么。也可以使用字典跟踪计数。但是,作为内存与代码权衡的一种方式,我选择使用两组而不是一个字典:

// 1. Data structure to track items we've seen
var found = new HashSet<Tuple<string, int>>();

// 2. Data structure to track items we should output
var output = new HashSet<Tuple<string, int>>();

// 3. Loop over the input data, storing it into `found`
using (var input = File.OpenText(path))
{
    string line;
    while (null != (line = input.ReadLine()))
    {
        // 4. Do your CSV parsing
        var parts = line.Split(','); // <- need better CSV parsing
        var item = Tuple.Create(parts[0], Int32.Parse(parts[1]));

        // 5. Track items we've found and those we should output
        // NB: HashSet.Add returns `false` if it already exists,
        // so we use that as our criteria to mark the item for output
        if (!found.Add(item)) output.Add(item);
    }
}

// 6. Output the items
// NB: you could put this in the main loop and borrow the same strategy
// we used for `found` to determine when to output an item so that only
// one pass is needed to read and write the data.
于 2012-05-07T12:58:55.087 回答
1

在不知道具体细节的情况下,我会采取的第一步是研究一个 Linq To CVS 库,比如这个......

http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library

于 2012-05-07T12:59:59.250 回答