我有一个记录列表,我需要在其中过滤列表中的重复记录,并使用 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/