在C#中,我有以下类:
public class SQLColour
{
public string ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string CorporateID { get; set; }
}
我有一个名为List1的List<SQLColour>
和一个名为List2的List<SQLColour>
。
如何返回List<SQLColour>
具有List1中存在但不存在于List2中的ID的项目?
提前致谢
答案 0 :(得分:1)
我通常使用以下模式,因为Enumerable.Except不接受通用谓词:
// Find all IDs in List2, using a HashSet to improve bounds
var idsList2 = new HashSet(List2.Select(x => x.Id));
// Select from List1 only elements which ID does not appear in List2
var onlyList1ById = List1.Where(x => !idsList2.Contains(x.Id));
HashSet不是必需的,但它有更好的界限,因此是我的标准模式。