使用HashSet在列表中添加新的不同子列表
问题描述:
仅当列表Zlist
中的子列表与其他子列表不同时,我想在列表Zlist
中添加新的子列表subroute
。这里是Zlist
的定义和初始sublists
:使用HashSet在列表中添加新的不同子列表
HashSet<Matrix> Zlist = new HashSet<Matrix>();
for (int m = 0; m < M; m++)
{
for (int i = 1; i < C + 1; i++)
{
Zlist.Add(new Matrix() {Column = {m,i}});
}
}
这里是<Matrix>
定义:
class Matrix
{
public List<int> Column { get; set; }
public Matrix()
{
Column = new List<int>();
}
}
这是我怎么加我的subroute
到Zlist
:
foreach (var subroute in route)
Zlist.Add(new Matrix() { Column = subroute});
在我的情况,另一个名为route
的列表包含2个subroute
。哪一个是新的。但根据我的代码,Zlist
仍然添加全部subroute
。我已经把HashSet,但它没有奏效。请帮助,谢谢
答
你必须告诉HashMap如何做比较,因为这些都是引用类型。
public class MatrixComparer : IEqualityComparer<Matrix>
{
public bool Equals(Matrix x, Matrix y)
{
if (x.Column.Count != y.Column.Count) return false;
return !x.Column.Where((t, i) => t != y.Column[i]).Any();
}
public int GetHashCode(Matrix obj)
{
return obj.Column.Aggregate((i1, i2) => i1^i2);
}
}
而在HashMap中发送:
HashSet<Matrix> Zlist = new HashSet<Matrix>(new MatrixComparer());
请不要在提问标题重复的标签。 –