2017-02-23 1 views
0

하위 목록이 목록 Zlist의 다른 하위 목록과 다른 경우에만 subroute을 목록 Zlist에 추가하려고합니다. 여기 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>의 정의입니다 : 여기에 Zlist의 정의와 초기 sublists입니다

class Matrix 
{ 
    public List<int> Column { get; set; } 

    public Matrix() 
    { 
     Column = new List<int>(); 
    } 
} 

는 그리고 이것은 내가 추가하는 방법입니다 내 subrouteZlist에 :

foreach (var subroute in route) 
    Zlist.Add(new Matrix() { Column = subroute}); 

에서 내 경우에 route이라는 다른 목록에는 2 subroute이 포함되어 있습니다. 하나만 새로운 것입니다. 하지만 코드에 따라 Zlist은 여전히 ​​subroute을 모두 추가합니다. 이미 HashSet을 넣었지만 작동하지 않습니다. 도와주세요, 고마워요

+0

질문 제목에 태그를 반복하지 마십시오. –

답변

0

참조 유형이기 때문에 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());