C #에서 배열을 비교하는 방법은 무엇입니까? [복제]
중복 가능성 :
C #에서 배열을 비교하는 가장 쉬운 방법
C #에서 두 배열을 어떻게 비교할 수 있습니까?
다음 코드를 사용하지만 그 결과는 거짓입니다. 나는 그것이 사실 일 것이라고 기대하고 있었다.
Array.Equals(childe1,grandFatherNode);
System.Linq의 Enumerable.SequenceEqual ()을 사용하여 배열의 내용을 비교할 수 있습니다.
bool isEqual = Enumerable.SequenceEqual(target1, target2);
객체 참조를 비교하고 있지만 동일하지 않습니다. 배열 내용을 비교해야합니다.
.NET2 솔루션
옵션은 배열 요소를 반복 Equals()
하고 각 요소를 호출하는 것 입니다. Equals()
동일한 개체 참조가 아닌 경우 배열 요소에 대한 메서드 를 재정의해야합니다 .
대안은이 일반 방법을 사용하여 두 개의 일반 배열을 비교하는 것입니다.
static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1, a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i])) return false;
}
return true;
}
.NET 3.5 이상 솔루션
또는 Linq를 사용할 수있는 경우 SequenceEqual을 사용 합니다 (.NET Framework> = 3.5).
클래스 에는 정적 Equals
메서드 가 없으므로 Array
실제로 사용 Object.Equals
하는 것은 두 개체 참조가 동일한 개체를 가리키는 지 확인하는입니다.
배열에 동일한 순서로 동일한 항목이 포함되어 있는지 확인하려면 SequenceEquals
확장 메서드를 사용할 수 있습니다 .
childe1.SequenceEqual(grandFatherNode)
편집하다:
사용하려면 SequenceEquals
다차원 배열과 함께, 당신은 그 (것)들을 열거 확장을 사용할 수 있습니다. 다음은 2 차원 배열을 열거하는 확장입니다.
public static IEnumerable<T> Flatten<T>(this T[,] items) {
for (int i = 0; i < items.GetLength(0); i++)
for (int j = 0; j < items.GetLength(1); j++)
yield return items[i, j];
}
용법:
childe1.Flatten().SequenceEqual(grandFatherNode.Flatten())
배열에 2 개 이상의 차원이있는 경우 해당 차원 수를 지원하는 확장이 필요합니다. 차원 수가 다른 경우 가변 차원 수를 반복하려면 좀 더 복잡한 코드가 필요합니다.
You would of course first make sure that the number of dimensions and the size of the dimensions of the arrays match, before comparing the contents of the arrays.
Edit 2:
Turns out that you can use the OfType<T>
method to flatten an array, as RobertS pointed out. Naturally that only works if all the items can actually be cast to the same type, but that is usually the case if you can compare them anyway. Example:
childe1.OfType<Person>().SequenceEqual(grandFatherNode.OfType<Person>())
Array.Equals
is comparing the references, not their contents:
Currently, when you compare two arrays with the = operator, we are really using the System.Object's = operator, which only compares the instances. (i.e. this uses reference equality, so it will only be true if both arrays points to the exact same instance)
If you want to compare the contents of the arrays you need to loop though the arrays and compare the elements.
The same blog post has an example of how to do this.
The Equals
method does a reference comparison - if the arrays are different objects, this will indeed return false.
To check if the arrays contain identical values (and in the same order), you will need to iterate over them and test equality on each.
Array.Equals() appears to only test for the same instance.
There doesn't appear to be a method that compares the values but it would be very easy to write.
Just compare the lengths, if not equal, return false. Otherwise, loop through each value in the array and determine if they match.
참고URL : https://stackoverflow.com/questions/4423318/how-to-compare-arrays-in-c
'program tip' 카테고리의 다른 글
WPF에서 더미 디자인 타임 데이터에 사용할 수있는 접근 방식은 무엇입니까? (0) | 2020.08.27 |
---|---|
C ++에 파일이 있는지 확인하는 가장 좋은 방법은 무엇입니까? (0) | 2020.08.26 |
Linux의 Bash에서 한 번에 여러 파일을 삭제하는 방법은 무엇입니까? (0) | 2020.08.26 |
신속하게 좌표를 사용하여 프로그래밍 방식으로지도 앱을 여는 방법은 무엇입니까? (0) | 2020.08.26 |
숫자의 총 자릿수를 어떻게 구할 수 있습니까? (0) | 2020.08.26 |