开发者

C# - Working with values in a Dictionary

This may be a simple question, but I can't figure out a simple way of doing this. I currently have a simple dictionary with KeyValuePairs like the following:

<1, 100> <2, 200> <3, -999> <4, 134> <5, -999> <6, 223> <7, 123>

The value's (-999) are an indicator for an error that occurs. What I am trying to do is iterate through the dictionary and for whenever there occurs a -999 use the value for the following key. Th开发者_StackOverflowe result, given the above example, would be:

<1, 100> <2, 200> <3, 134> <4, 134> <5, 223> <6, 223> <7, 123>

Any thoughts would be much appreciated!


You need to assume that your keys have an ordering (this is necessary because dictionaries otherwise don't have an ordering). You might want to consider using a SortedDictionary.

Either way, you can say:

var keys = dictionary.Keys.OrderByDescending(k => k);
int current = -999;
foreach (var key in keys) {
    if (dictionary[key] == -999) {
        dictionary[key] = current;
    }
    current = dictionary[key];
}

Note that you didn't specify what to do if the "last" item is -999. For now it remains at -999.


Do you have access to the n+1-th element when you're adding the nth element? If so, you could substitute n+1-th value when you add nth key.

If not then you need an ordered collection. I'm not sure SortedDictionary would be what you need becuase the keys might not be your sort order? It is also puzzling that you list several K,V pairs with identical keys. Dictionaries won't like that.

Is the key within the V? Like an ID property? If so, You could try to derive a class from KeyedCollection which preserves the order in which you added items and lets you decide what property of the value is the key if it works that way for you. But again, no duplicate keys.


I'm going to assume that you want to process the values in the order they are added to the dictionary, and not the order they might happen to sort in. I think you might be better off using a Stack<>. This way you can push all the KeyValuePairs onto the stack, then pop them off backwards. When you find a -999 you can apply the value of the previous KeyValuePair that was popped off the stack and move on.


If you don't need them in a dictionary you could use a linked list, then you could start at the end and loop through the list to update the -999 values.

LinkedList<KeyValuePair<int, int>> myList = GetMyKeyValues();

LinkedListNode<KeyValuePair<int, int>> curr = myList.Last;
LinkedListNode<KeyValuePair<int, int>> last = null;

while (curr != null)
{
    if (curr.Value == -999 && last != null)
    {
        curr.Value = last.Value;
    }

    last = curr;
    curr = curr.Previous;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜