我有一个记录列表,我需要过滤该列表中的重复记录,并仅使用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”来获取记录,并且上面的查询随机选择了First记录.我在此查询中尝试了另一件事,但它不起作用:
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(),我可以处理null错误,但是该行的详细信息不会添加到结果中.有什么想法吗?
解决方法:
尝试将谓词放在对first的调用中:
var filteredData = data
.GroupBy(x => x.Id)
.Select(x => x.FirstOrDefault(x => x.AddressType == "POST"))
.ToList();