2016-07-14 2 views
1

두 개의 컬렉션이 있고 각 요소를 반복하고 각 컬렉션의 해당 요소를 비교하여 컬렉션이 동일한 지 여부를 확인합니다.두 컬렉션을 반복하여 C에서 동일한 컬렉션을 비교합니다.

foreach 루프를 사용할 수 있습니까? 아니면 카운터를 사용하여 요소를 인덱스별로 액세스해야합니까?

일반적으로 연산자를 과부하하는 것과 같이 컬렉션을 비교하는 데 선호되는 방법이 있습니까?

TIA.

+0

가능한 중복 [? C#에서 컬렉션을 비교하는 기본 방법이있다 (http://stackoverflow.com/questions/43500/is- built-in-method-to-compare-collection-in-c) – Ivan

답변

4

이 목적으로 사용되는 .SequenceEqual 방법을 사용할 수 있습니다. More을 읽으십시오.

링크가 작동 중지되었거나 제거 된 경우 아래의 예입니다.

요소를 해당 형식에 대해 기본 동일성 비교자를 사용하여 비교하여 두 시퀀스가 ​​같은지 여부를 확인합니다.

SequenceEqual은 (는 IEnumerable,는 IEnumerable) 방법은 병렬로 두 소스 시퀀스를 열거하고 TSource, 초기의 기본 같음 비교하여 해당 요소를 비교한다. 기본 동등 비교자인 기본값 인 은 IEqualityComparer 일반 인터페이스를 구현하는 유형의 값을 비교합니다. 사용자 지정 데이터 형식을 비교하려면 이 인터페이스를 구현하고 형식에 대해 고유 한 GetHashCode 및 Equals 메서드를 제공해야합니다.

당신이 순서 대신 그들의 참조를 비교의 개체의 실제 데이터를 비교하려면

class Pet 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

public static void SequenceEqualEx1() 
{ 
    Pet pet1 = new Pet { Name = "Turbo", Age = 2 }; 
    Pet pet2 = new Pet { Name = "Peanut", Age = 8 }; 

    // Create two lists of pets. 
    List<Pet> pets1 = new List<Pet> { pet1, pet2 }; 
    List<Pet> pets2 = new List<Pet> { pet1, pet2 }; 

    bool equal = pets1.SequenceEqual(pets2); 

    Console.WriteLine(
     "The lists {0} equal.", 
     equal ? "are" : "are not"); 
} 

/* 
    This code produces the following output: 

    The lists are equal. 
*/ 

, 당신은 클래스의 IEqualityComparer 제네릭 인터페이스를 구현해야합니다. 다음 코드 예제는이 인터페이스를 사용자 지정 데이터 형식으로 구현하고 GetHashCode 및 Equals 메서드를 제공하는 방법을 보여줍니다.

public class Product : IEquatable<Product> 
{ 
    public string Name { get; set; } 
    public int Code { get; set; } 

    public bool Equals(Product other) 
    { 

     //Check whether the compared object is null. 
     if (Object.ReferenceEquals(other, null)) return false; 

     //Check whether the compared object references the same data. 
     if (Object.ReferenceEquals(this, other)) return true; 

     //Check whether the products' properties are equal. 
     return Code.Equals(other.Code) && Name.Equals(other.Name); 
    } 

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects. 

    public override int GetHashCode() 
    { 

     //Get hash code for the Name field if it is not null. 
     int hashProductName = Name == null ? 0 : Name.GetHashCode(); 

     //Get hash code for the Code field. 
     int hashProductCode = Code.GetHashCode(); 

     //Calculate the hash code for the product. 
     return hashProductName^hashProductCode; 
    } 
} 

사용법 :

Product[] storeA = { new Product { Name = "apple", Code = 9 }, 
          new Product { Name = "orange", Code = 4 } }; 

Product[] storeB = { new Product { Name = "apple", Code = 9 }, 
          new Product { Name = "orange", Code = 4 } }; 

bool equalAB = storeA.SequenceEqual(storeB); 

Console.WriteLine("Equal? " + equalAB); 

/* 
    This code produces the following output: 

    Equal? True 
*/ 
+0

왜'return Code == other.Code && Name == other.Name;'? 'Code'와'Name' ('int'와'string')의 타입은'=='와 잘 맞는 씰 타입입니다. 'Name.Eqauls'를 가진 당신의 솔루션은'Name'이'null' ('GetHashCode'에서 다루기로 한 상황)이라면 폭발 할 것입니다. –

+0

@JeppeStigNielsen 앞에서 설명한대로이 예제는 MSDN에서 직접 가져온 것입니다. – user3185569

+0

그것이 나를 비난하는 것을 막지는 못합니다. –

관련 문제