해당 PCL 프로필에 "정렬 된"컬렉션이 없습니다. 따라서 다른 컬렉션에서 Sort
메서드를 호출하여 정렬하거나 자체 정렬 컬렉션을 작성해야합니다. 컬렉션이 필요하면 간단한 바이너리 검색/삽입을 사용하여 항목을 컬렉션에 추가 할 때 항목을 정렬 할 수 있습니다. 다음과 같이 수있는 백업 List<T>
를 사용하는 예 :
public class SortedCollection<T> : ICollection<T>
{
private readonly List<T> collection = new List<T>();
// TODO: initializable:
private readonly IComparer<T> comparer = Comparer<T>.Default;
public void Add(T item)
{
if (Count == 0)
{
collection.Add(item);
return;
}
int minimum = 0;
int maximum = collection.Count - 1;
while (minimum <= maximum)
{
int midPoint = (minimum + maximum)/2;
int comparison = comparer.Compare(collection[midPoint], item);
if (comparison == 0)
{
return; // already in the list, do nothing
}
if (comparison < 0)
{
minimum = midPoint + 1;
}
else
{
maximum = midPoint - 1;
}
}
collection.Insert(minimum, item);
}
public bool Contains(T item)
{
// TODO: potential optimization
return collection.Contains(item);
}
public bool Remove(T item)
{
// TODO: potential optimization
return collection.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return collection.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Clear()
{
collection.Clear();
}
public void CopyTo(T[] array, int arrayIndex)
{
collection.CopyTo(array, arrayIndex);
}
public int Count { get { return collection.Count; } }
public bool IsReadOnly { get { return false; } }
}
나는 작동 정렬 된 집합을 얻을 수있는 최소한의 일을했습니다. Contains
및 Remove
이 목록이 정렬되어 있음을 인식하고 O (n) 대신 O (log n) 검색을 수행하도록 최적화 할 수 있습니다.
다른 알고리즘이 더 빠를 수 있습니다. 계속 진행할 필요없이 간단하고 잘 이해 된 알고리즘을 선택했습니다.
[최신 버전의 설명서] (http://msdn.microsoft.com/en-us/library/vstudio/dd412070%28v=vs.110%29.aspx)로 이동하면 PCL/Windows Phone/Windows Store가 지원됩니다. –
@ Patrykíwiek 이것을 지적 해 주셔서 감사합니다. 그러나 .NET 4.0을 지원해야합니다. 나는 그 질문을 갱신했다. – Crono
오, 죄송합니다. 내가 말할 수있는 한, 당신은 운이 없으며, 제 3 자 솔루션을 사용하거나 자신의 구현을 롤아웃해야합니다. –