c# - Linq 中 GroupBy 的案例条件用于重复记录

标签 c# linq duplicates

我有一个记录列表,我需要在其中过滤列表中的重复记录,并使用 AddressType = "POST" 只获取一条记录。

让我举个例子:

class Test
{
public string Id {get; set;}
public string Name {get; set;}
public string AddressType {get; set;}
}

这是我的数据:

var data = new List<Test>{
                new Test {Id = "1", Name = "Test11", AddressType = "POST" },
                new Test {Id = "1", Name = "Test12", AddressType = "STREET" },
                new Test {Id = "2", Name = "Test122", AddressType = "POST" },
                new Test {Id = "3", Name = "Test123", AddressType = "POST" },
                new Test {Id = "4", Name = "Test1", AddressType = "POST" },
                new Test {Id = "4", Name = "Test1", AddressType = "POST" },
                new Test {Id = "5", Name = "Test11", AddressType = null }
            };

我试图通过此查询删除基于 Id 和 AdressType = "POST"的重复记录:

var filteredData = data.GroupBy(x => x.Id).Select(x => x.First()).ToList();

这消除了重复,但我想获取 AddressType = "POST"的记录,上面的查询随机选择了第一条记录。我在这个查询中尝试了另一件事,但它不起作用:

var filteredData = data.GroupBy(x => x.Id).Select(x => x.First()).Where(x => x.AddressType == "POST").ToList();

预期输出:

Test {Id = "1", Name = "Test11", AddressType = "POST" }, 
Test {Id = "2", Name = "Test122", AddressType = "POST" }, 
Test {Id = "3", Name = "Test123", AddressType = "POST" },
Test {Id = "4", Name = "Test1", AddressType = "POST" },
Test {Id = "5", Name = "Test11", AddressType = null }

有什么我遗漏的吗?

更新:由于下面的解决方案,它起作用了,但在列表中有任何空值的情况下。它坏了。因此,通过添加 FirstOrDefault() 我能够处理空错误,但该行的详细信息不会添加到结果中。对此有什么想法吗?

最佳答案

尝试将谓词放在对 first 的调用中:

var filteredData = data
   .GroupBy(x => x.Id)
   .Select(x => x.FirstOrDefault(x => x.AddressType == "POST"))
   .ToList();

关于c# - Linq 中 GroupBy 的案例条件用于重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46968544/

相关文章:

c# - 如何在两个深度级别上执行双重包含?

c# - C#在扩展方法中指定orderby

列表性能中的Python模糊匹配字符串

c# - 淡化面板 - Windows 窗体

c# - 调用堆栈和评估堆栈如何关联?

c# - LINQ:如何使用 group by 子句获取 Max Id?

Python - 在新列中保留接近重复行的不同值,然后删除重复项

ios - 根据键的值从 NSDictionary 的 NSMutableArray 中删除重复项

c# - 这种情况如何实现GetHashCode?

c# - 我可以为外部硬盘写一个扩展吗