C #에서 두 배열 간의 "차이"를 얻습니까?
이 두 배열이 있다고 가정 해 봅시다.
var array1 = new[] {"A", "B", "C"};
var array2 = new[] {"A", "C", "D"};
나는 둘 사이의 차이점을 얻고 싶습니다. 몇 줄의 코드로 작성할 수 있다는 것을 알고 있지만 기본 제공 언어 기능이나 LINQ 확장 메서드가 누락되지 않았는지 확인하고 싶습니다.
이상적으로는 다음 세 가지 결과를 얻습니다.
- array1에 없지만 array2에있는 항목 ( "D")
- array2에 없지만 array1에있는 항목 ( "B")
- 둘 다에있는 항목
미리 감사드립니다!
LINQ를 사용할 수있는 경우 Except
및 Distinct
. 질문에서 요청한 세트는 각각 다음과 같습니다.
- array2.Except(array1)
- array1.Except(array2)
- array1.Intersect(array2)
로부터 MSDN 101 LINQ 샘플 ....
public void Linq52() {
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);
Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers) {
Console.WriteLine(n);
}
}
다음은 LINQ 확장 방법의 벤치 마크입니다. 결과는 실제 프로그램을 개발하는 동안 얻었습니다.
테스트 : 2 개의 목록 (lst1 및 lst2)은 각각 약 250000 개 개체입니다. 각 객체 (클래스 Key)에는 문자열과 정수가 포함됩니다. 두 번째 목록에는 대부분 첫 번째 목록과 동일한 항목이 포함되어 있지만 일부 새 항목이 추가되고 일부는 제거됩니다.
Except 확장 방법을 테스트했습니다.
var except = lst2.Except (lst1);
목록 lst = except.ToList ();
이 2 개 라인은 600 개의 "새 추가"항목 목록을 생성했습니다. StopWatch 객체를 사용하여 시간을 측정했습니다. 속도는 놀랍습니다 : 220ms . 내가 사용한 컴퓨터는 결코 "빠른 곤잘레스"가 아닙니다. Core 2 Duo T7700 – 2.4GHz.
노트 :
다음은 IEquatable i-face를 구현하는 Key 클래스입니다.
public class Key : IEquatable<Key>
{
public int Index { get; private set; }
public string Name { get; private set; }
public Key(string keyName, int sdIndex)
{
this.Name = keyName;
this.Index = sdIndex;
}
// IEquatable implementation
public bool Equals(Key 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 Index.Equals(other.Index) && 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 hashKeyName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the index field.
int hashKeyIndex = Index.GetHashCode();
//Calculate the hash code for the Key.
return hashKeyName ^ hashKeyIndex;
}
}
I've had to do things similar to this with very large sets of data. If you're dealing with a few thousand or so, use the Linq stuff since it's much clearer. But if you know that your arrays are pre-sorted, running a merge like this can do it significantly faster, since it only makes one pass through the data and doesn't need to allocate as much memory as the Linq version.
int iA = 0;
int iB = 0;
List<int> inA = new List<int>();
List<int> inB = new List<int>();
List<int> inBoth = new List<int>();
while (iA < numbersA.Length && iB < numbersB.Length)
{
if (numbersA[iA] < numbersB[iB])
{
inA.Add(numbersA[iA++]);
}
else if (numbersA[iA] == numbersB[iB])
{
inBoth.Add(numbersA[iA++]);
++iB;
}
else
{
inB.Add(numbersB[iB++]);
}
}
while (iA < numbersA.Length)
{
inA.Add(numbersA[iA++]);
}
while (iB < numbersB.Length)
{
inB.Add(numbersB[iB++]);
}
Again, this is really only needed if you are dealing with hundreds of thousands of values.
Another solution would be like below as well
int[] arr1 = new int[] { 45, 26, 99, 55, 36 };
int[] arr2 = new int[] { 45, 26, 99, 20, 36 };
var res = arr1.Union(arr2).Except(arr1.Intersect(arr2));
ReferenceURL : https://stackoverflow.com/questions/683310/getting-the-diff-between-two-arrays-in-c
'program story' 카테고리의 다른 글
루트 컨텍스트를 어떻게 지정합니까? (0) | 2020.12.24 |
---|---|
파이썬에서 연결이 끊어 졌는지 확인하는 방법 (0) | 2020.12.24 |
이 C # 프로그램에서 인쇄 할 열 이름을 어떻게 얻습니까? (0) | 2020.12.15 |
슬라이스 표기법을 사용하여 목록 반전 (0) | 2020.12.15 |
AVD 에뮬레이터에서 sdcard 폴더를 보는 방법은 무엇입니까? (0) | 2020.12.15 |