2017-11-23 1 views
0

필드가있는 항목의 모음 클래스가 있습니다.지정된 필드에 의해 구분되고 다른 필드는 무시되지만 너무 깁니다.

class Item 
{ 
    string s1; 
    string s2; 
    string s3; 
    string d1; 
    string d2; 
} 

MyCollection은 다음과 같습니다

public class MyCollection : ICollection<Item>, IEnumerable 
{} 

내가 S1, S2 (모든 필드 목록을 'S1', 'S2', 'S3'이 아니라 대가로 구별에 그 목록이 필요 , s3, d1, d2), 중복 항목없이. 그래서 다른 말로하면, 그 대가로 나는 지금은

var list = source.Select(k => new { k.s1, k.s2, k.s2 }).Distinct().ToList();

같은 것을 가지고 있지만 그것은 단지 S1, S2, S3 필드 목록을 반환 들어 MyCollection<Item>하지 List<anonymousType>

이 필요합니다.

어떤 방법이 있습니까?

+0

어떤'd1'와'd2'을 할 수 있습니까? 당신은 distinct 대신에'GroupBy'를 가지고 시작할 수 있습니다. 그러면'Select (x => 새로운 항목 {s1 = x.s1, ...}', 몇 가지 옵션이 있지만 선택할 항목을 알아야합니다 'd1, d2' – oerkelens

답변

3

당신은 IEqualityComparer <>을 만들 수 있습니다. 주어진`S1, S2, s3`하기에 여러 값을 가질 때

class ItemComparer : IEqualityComparer<Item> 
{ 
    public bool Equals(Item x, Item y) 
    { 
     if (ReferenceEquals(x, y)) return true; 
     if (ReferenceEquals(x, null)) return false; 
     if (ReferenceEquals(y, null)) return false; 
     if (x.GetType() != y.GetType()) return false; 

     return x.s1 == y.s1 && x.s2 == y.s2 && x.s3 == y.s3; 
    } 

    public int GetHashCode(Item obj) 
    { 
     var hashCode = obj.s1.GetHashCode(); 
     hashCode = (hashCode * 397)^obj.s2.GetHashCode(); 
     hashCode = (hashCode * 397)^obj.s3.GetHashCode(); 
     return hashCode; 
    } 
} 

그런 다음 당신은 당신이 원하는 게이

var distinctList = list.Distinct(new ItemComparer()).ToList(); 
+0

GetHashCode 메서드 구현을 설명해 주시겠습니까? –

+0

해시 코드는 고유해야합니다. 기본적으로 세 문자열의 해시를 매우 고유해야하는 것으로 결합합니다. – sQuir3l

관련 문제