c# - 在 csv 文件中查找重复项目

标签 c# csv

我有一个 CSV 文件

FirstName LastName and ID column, Id is an Unique Column

Chris, Webber, 1 
Chris, Ben, 2
Chris, Dudley, 3
David, Floy, 4
Chris, Ben, 5 
Chris, Webber, 6

我需要在不使用数据库的情况下获得两个列表,我需要从 C# 中的文件中读取它并创建两个列表重复列表和原始列表。

重复列表包含所有重复项

Chris, Webber, 1
Chris, Webber, 6
Chris, Ben, 2
Chris, Ben, 5

原始列表具有唯一的条目和第一次出现的重复条目。

Chris, Webber, 1
Chris, Ben, 2
Chris, Dudley, 3
David, Floy, 4

What is the best way solve this?

最佳答案

var lines = File.ReadLines("yourFile.ext");

// this assumes you can hold the whole file in memory

// uniqueness is defined by the first two columns
var grouped = lines.GroupBy(line => string.Join(", ", line.Split(',').Take(2)))
                   .ToArray();

// "unique entry and first occurrence of duplicate entry" -> first entry in group
var unique = grouped.Select(g => g.First());

var dupes = grouped.Where(g => g.Count() > 1)
                   .SelectMany(g => g);

Console.WriteLine("unique");
foreach (var name in unique)
    Console.WriteLine(name);

Console.WriteLine("\nDupes");
foreach (var name in dupes)
    Console.WriteLine(name);

输出:

unique
Chris, Webber, 1
Chris, Ben, 2
Chris, Dudley, 3
David, Floy, 4

Dupes
Chris, Webber, 1
Chris, Webber, 6
Chris, Ben, 2
Chris, Ben, 5

关于c# - 在 csv 文件中查找重复项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578252/

相关文章:

python - 使用 pandas 将字符串对象转换为 int/float

c# - 在 Windows Phone 8 中禁用浏览器链接

c# - 在 Azure 上打开注册页面时出现 "502 - Web server received an invalid response while acting as a gateway or proxy server"错误

php - CSV 文件使用 php 不断更改生成的 CSV 文件上的数字?

python - 在 Python 中根据 .csv 文件绘制正态分布

php - 在 PHP 中将 CSV 文件解析到 MySQL DB

excel - 用于 Excel 的开源 JDBC 驱动程序,Maven 存储库上的 CSV 文件

c# - 检查 T 泛型类型是否具有 C# 中的属性 S(泛型)

c# - Linq 到实体查询

托管在 Windows 服务中的 c# wcf 在 5 分钟后空闲