이것은 오래된 질문이며 이전에 기존 답변을 직접 사용해 보았습니다. 그러나 KeyedCollection <>을 다시 한번 들으면서, Remove-and-Then-Add 기술이 지금 구현 한 기술보다 효율적이지 않다는 것을 알게되었습니다. 문제는 Remove() 메서드가 List를 선형으로 검색 한 다음 나머지 목록을 한 항목 왼쪽으로 이동한다는 것입니다. 여기서 제시 한 기술은 List를 선형 적으로 검색하지만 적어도 List의 나머지 부분은 이동하지 않습니다.
NB. 이는 대체 항목이 교체 할 항목과 동일한 키를 가지고있는 경우에만 적용 할 수 있습니다.
/// <summary>
/// Derived (but still abstract) version of KeyedCollection{} to provide a couple of extra
/// services, in particular AddOrReplace() and Replace() methods.
/// </summary>
public abstract class KeyedList<TKey, TItem> : KeyedCollection<TKey, TItem>
{
/// <summary>
/// Property to provide access to the "hidden" List{} in the base class.
/// </summary>
public List<TItem> BaseList
{
get { return base.Items as List<TItem>; }
}
/// <summary>
/// Method to add a new object to the collection, or to replace an existing one if there is
/// already an object with the same key in the collection.
/// </summary>
public void AddOrReplace(TItem newObject)
{
int i = GetItemIndex(newObject);
if (i != -1)
base.SetItem(i, newObject);
else
base.Add(newObject);
}
/// <summary>
/// Method to replace an existing object in the collection, i.e., an object with the same key.
/// An exception is thrown if there is no existing object with the same key.
/// </summary>
public void Replace(TItem newObject)
{
int i = GetItemIndex(newObject);
if (i != -1)
base.SetItem(i, newObject);
else
throw new Exception("Object to be replaced not found in collection.");
}
/// <summary>
/// Method to get the index into the List{} in the base collection for an item that may or may
/// not be in the collection. Returns -1 if not found.
/// </summary>
private int GetItemIndex(TItem itemToFind)
{
TKey keyToFind = GetKeyForItem(itemToFind);
return BaseList.FindIndex((TItem existingItem) =>
GetKeyForItem(existingItem).Equals(keyToFind));
}
}
'사전'을 사용하십시오. 왜/어떻게 처음에'KeyedCollection'을 사용하고 있습니까? – jeroenh
KeyedCollection은 기본 제공 키가있는 모델링 객체로 이동하는 방법으로 권장됩니다. 나는 지금까지 기존의 기록을 대체해야한다는 상황에 결코 빠져들지 않았으며, 그 점에 대해서는 약간 제한적이라는 것을 인식하지 못했습니다. – RobinHood70
기다려라 ... 나는 사전과 함께 할 때와 마찬가지로 Remove/Add를 할 수있다. 결국 KeyedCollection에서 벗어날 필요가 없을 것입니다. – RobinHood70