我有一个包含对象的列表,但这些对象在列表中不是唯一的.我想这个代码在另一个列表中使它们独一无二:
foreach (CategoryProductsResult categoryProductsResult in categoryProductsResults.Where(categoryProductsResult => !resultSet.Contains(categoryProductsResult)))
{
resultSet.Add(categoryProductsResult);
}
Run Code Online (Sandbox Code Playgroud)
但最后resultSet与categoryProductsResults相同.
categoryProductsResult的第二行:

resultSet第一行:

正如您所看到的,resultSet的第一行和categoryProductsResult的第二行是相同的,但它将第二行添加到resultSet.
你有什么建议吗?
Tim*_*ter 13
Contains使用默认的比较器,它比较引用,因为你的类没有覆盖Equals和GetHashCode.
class CategoryProductsResult
{
public string Name { get; set; }
// ...
public override bool Equals(object obj)
{
if(obj == null)return false;
CategoryProductsResult other = obj as CategoryProductsResult;
if(other == null)return false;
return other.Name == this.Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以简单地使用:
resultSet = categoryProductsResults.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)