这是故事:
我试图列出不同的集群...我只想拥有必要的集群......而集群可以是相同的.
如何通过检查列表是否包含对象(我知道对象不能在此处传递)将其添加到列表中
这是我的样本报价:
foreach (Cluster cluster in clustersByProgramme)
{
if (!clusterList.Contains(cluster))
{
clusterList.Add(cluster);
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码应该有效; 如果没有,您可能正在使用代表相同实际集群的不同对象实例,并且您可能没有提供合适的Equals实现(您还应该同时更新GetHashCode).
另外 - 在.NET 3.5中,这可能很简单:
var clusterList = clustersByProgramme.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
作为支持相等测试的类的示例:
class Cluster // possibly also IEquatable<Cluster>
{
public string Name { get { return name; } }
private readonly string name;
public Cluster(string name) { this.name = name ?? ""; }
public override string ToString() { return Name; }
public override int GetHashCode() { return Name.GetHashCode(); }
public override bool Equals(object obj)
{
Cluster other = obj as Cluster;
return obj == null ? false : this.Name == other.Name;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |