작은 바이트 목록이 있고 모두 다른 값인지 테스트하고 싶습니다. 예를 들어 다음과 같습니다.
List<byte> theList = new List<byte> { 1,4,3,6,1 };
모든 값이 구별되는지 확인하는 가장 좋은 방법은 무엇입니까?
답변
bool isUnique = theList.Distinct().Count() == theList.Count();
답변
여기에 Enumerable.Distinct
+ 보다 더 효율적인 또 다른 접근법이 있습니다 Enumerable.Count
(시퀀스가 컬렉션 유형이 아닌 경우 더욱 그렇습니다). 그것은 사용하는 HashSet<T>
중복을 제거하는이 조회에서 매우 효율적이며 카운트 속성이 있습니다 :
var distinctBytes = new HashSet<byte>(theList);
bool allDifferent = distinctBytes.Count == theList.Count;
또는 다른-더 미묘하고 효율적인 접근법 :
var diffChecker = new HashSet<byte>();
bool allDifferent = theList.All(diffChecker.Add);
HashSet<T>.Add
반환 false
는 이미 이후 요소를 추가 할 수없는 경우 HashSet
. Enumerable.All
첫 번째 “거짓”에서 중지합니다.
답변
좋습니다. 여기에 표준 .Net을 사용하는 가장 효율적인 방법이 있습니다.
using System;
using System.Collections.Generic;
public static class Extension
{
public static bool HasDuplicate<T>(
this IEnumerable<T> source,
out T firstDuplicate)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
var checkBuffer = new HashSet<T>();
foreach (var t in source)
{
if (checkBuffer.Add(t))
{
continue;
}
firstDuplicate = t;
return true;
}
firstDuplicate = default(T);
return false;
}
}
기본적으로 전체 시퀀스를 두 번 열거하는 요점은 첫 번째 복제본을 찾는 것뿐입니다.
빈 단일 요소 시퀀스를 특수 케이스로 처리하여이를 더 최적화 할 수 있지만 최소한의 이득으로 가독성 / 유지 보수 가능성이 떨어집니다.
답변
Distinct
사용 과 유사한 논리 GroupBy
:
var isUnique = theList.GroupBy(i => i).Count() == theList.Count;
답변
또한 할 수있는 일 : Hashset 사용
var uniqueIds = new HashSet<long>(originalList.Select(item => item.Id));
if (uniqueIds.Count != originalList.Count)
{
}
답변
많은 해결책이 있습니다.
그리고 “juergen d”와 “Tim Schmelter”로 LINQ를 사용한 더 아름다운 것들은 의심 할 여지가 없습니다.
그러나 “복잡성”과 속도를 노출하지 않는다면 가장 좋은 해결책은 직접 구현하는 것입니다. 해결책 중 하나는 N 크기의 배열을 만드는 것입니다 (바이트의 경우 256). 그리고 배열을 반복하고 모든 반복에서 값이 1이면 일치하는 숫자 인덱스를 테스트합니다. 그렇다면 이미 배열 인덱스를 증가시키고 따라서 배열이 구별되지 않음을 의미합니다. 그렇지 않으면 배열 셀을 증가시키고 계속 확인합니다. .
답변
그리고 중복 된 값을 찾으려면 또 다른 솔루션입니다.
var values = new [] { 9, 7, 2, 6, 7, 3, 8, 2 };
var sorted = values.ToList();
sorted.Sort();
for (var index = 1; index < sorted.Count; index++)
{
var previous = sorted[index - 1];
var current = sorted[index];
if (current == previous)
Console.WriteLine(string.Format("duplicated value: {0}", current));
}
산출:
duplicated value: 2
duplicated value: 7
