Is there a way to track the ordering of items in a dictionary?

I have one Dictionary<Guid, ElementViewModel>. (ElementViewModel is our own complex type.) I add items to the stock standard dictionary items.Add(Guid.NewGuid, new ElementViewModel() { /*setters go here*/ });,

At a later stage, I delete some or all of these elements.

The simplest view of my ElementViewModel is this:

class ElementViewModel
{
    Guid Id { get; set; }
    string Name { get; set; }
    int SequenceNo { get; set; }
}

It may be important to note that SequenceNos are compacted into collections after adding, in the case of other operations such as moving and copying. {1, 5, 6} → {1, 2, 3}

The simplest kind of my delete operation:

public void RemoveElementViewModel(IEnumerable<ElementViewModel> elementsToDelete)
{
    foreach (var elementViewModel in elementsToDelete)
        items.Remove(elementViewModel.Id);

    CompactSequenceNumbers();
}

I will illustrate the problem with an example:

I add 3 words to the dictionary:

var newGuid = Guid.NewGuid();
items.Add(newGuid, new MineLayoutElementViewModel { Id = newGuid, SequenceNo = 1, Name = "Element 1" });
newGuid = Guid.NewGuid();
items.Add(newGuid, new MineLayoutElementViewModel { Id = newGuid, SequenceNo = 2, Name = "Element 2" });
newGuid = Guid.NewGuid();
items.Add(newGuid, new MineLayoutElementViewModel { Id = newGuid, SequenceNo = 3, Name = "Element 3" });

I delete 2 items

RemoveElementViewModel(new List<ElementViewModel> { item2, item3 }); //imagine I had them cached somewhere.

Now I want to add 2 more items:

newGuid = Guid.NewGuid();
items.Add(newGuid, new MineLayoutElementViewModel { Id = newGuid, SequenceNo = 2, Name = "Element 2, Part 2" });
newGuid = Guid.NewGuid();
items.Add(newGuid, new MineLayoutElementViewModel { Id = newGuid, SequenceNo = 3, Name = "Element 3, Part 2" });

, " 1", " 2, 2", " 3, 2"

: " 1", " 3, 2", " 2, 2"


, . , , ?

+5
3

, SortedDictionary , , KeyedCollection SequenceNo .

, , , :

, , , . , . , .

0

.Net .

KeyedCollection<TKey, TValue>; - .

:

class ElementViewModelCollection : KeyedCollection<Guid, ElementViewModel> {
    protected override Guid GetKeyForItem(ElementViewModel item) { return item.Id; }
}

items.Add(new MineLayoutElementViewModel { Id = Guid.NewGuid(), SequenceNo = 3, Name = "Element 3" });

, Id , ChangeItemKey . Id .

+14

Any reason you are not using System.Collections.Generic.SortedDictionary seems to be what you are looking for

+3
source

All Articles