C# 查询和比较 CSV 文件中的条目

本文关键字:文件 CSV 查询 比较 | 更新日期: 2023-09-27 18:33:27

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

狗 5

猫 7

老鼠 5

狗 3

狗 5

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

像往常一样感谢

C# 查询和比较 CSV 文件中的条目

如果你的模式真的这么简单,那么使用 TupleHashSet<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.

在不知道确切细节的情况下,我要采取的第一步是研究 Linq To CVS 库,例如这个...

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