我已经看到提到这样紧凑的答案的答案:here
List<T> withDupes = LoadSomeData();
List<T> noDupes = withDupes.Distinct().ToList();
所以我尝试了以下(语法)
List<InfoControl> withDupes = (List<InfoControl>)listBox1.ItemsSource;
listBox1.ItemsSource = withDupes.Distinct().ToList();
但是 withDupes 是 null 吗?也许我正在检索错误的数据列表。我一次添加了一个 InfoControl。
我还应该在 InfoControl 类中实现什么吗?(相等,哈希码)?
感谢附录 1:[忽略我不应该从 Java 翻译 :)] 在 InfoControl 类中声明了(从 Java 示例翻译,不确定它是否 100% 正确)..
public Boolean Equals(Object obj)
{ if (obj == this) { return true; }
if (!(obj is InfoControl)) { return false; }
InfoControl other = (InfoControl)obj;
return this.URL.Equals(other.URL); }
public int hashCode()
{ return this.URLFld.Content.GetHashCode(); }
附录 2:当我尝试使用基于 msdn 链接自定义类型示例的覆盖时,它说它是密封的 :) 通过 GetHashCode() 似乎并不明显,并且在不同之后我仍然得到相同的 listbox.items.count。
bool IEquatable<InfoControl>.Equals(InfoControl other)
{
if (Object.ReferenceEquals(other, null)) return false;
if (Object.ReferenceEquals(this, other)) return true;
return URL.Equals(other.URL);
}
public int GetHashCode(InfoControl obj)
{
return obj.URL.GetHashCode();
}
附录 3:当我尝试覆盖 VS2010 时说它是密封的?“无法覆盖继承的成员'System.Windows.DependencyObject.GetHashCode()',因为它是密封的”我做错了什么?
public override int GetHashCode()
{
return URL.GetHashCode();
}
public string URL
{
get { return this.URLFld.Content.ToString() ; }
set
{
this.URLFld.Content = value;
}
}
. 附录 4:
public partial class InfoControl : UserControl
, IEquatable<YouTubeInfoControl>
{
private string URL_;
public string URL
{
get { return URL_; }
set
{
URL_ = value;
}
}
bool IEquatable<YouTubeInfoControl>.Equals(YouTubeInfoControl other)
{
if (Object.ReferenceEquals(other, null)) return false;
if (Object.ReferenceEquals(this, other)) return true;
return URL == other.URL;
}
public override int GetHashCode()
{
return URL.GetHashCode();
}
}