How to move an item within a dictionary when the Key equals the order number?

c# dictionary
dictionary of dictionary in c#
c# reorder list

So I have a dictionary that looks something like this:

var newDictionary = new Dictionary<int, string>();

The int (key) within this dictionary is the oder number for the items.

So say I have a list like this

{ 1, "item1" } { 2, "item2" } { 3, "item3" } { 4, "item4" }

In my controller I pass what the old item order number was, and what the new order number should be. So for example if I wanted to move "item3" to be the first item I would pass to the controller 3 (old order number) and 1 (new order number). So my list would look like this:

{ 1, "item3" } { 2, "item1" } { 3, "item2" } { 4, "item4" }

This is not the type of thing you'd normally use a dictionary for. You could consider using a List instead of a Dictionary and use RemoveAt and InsertAt methods on the list. If your list gets very large you might need to consider an alternative way of doing things (for performance reasons) but for small amounts of data it should work just fine.

Manipulating Lists and Dictionaries in Python, Each element can be accessed using its position in the list. The same applies to your agenda, where you can modify the order in which you do things and even reschedule a number of tasks for the next day if needed. A dictionary is a mutable​, unordered set of key-value pairs where each key must be  How would I move a blue value say [0,1] to the red without leaving behind a copy in blue without hardcoding the delete ( so if I had a different list of a hundred values and want to move a value from one key to another it should also work in that way ). I want the output to look this: dictionary = {'blue': [ [0,2] ] , 'red': [ [0,3], [0,4], [0

Look on this like this:

You don's change items order, but change a value that key point's to. The effective order of items does not matter in dictionary, but what matters are keys that point to values.

What you want is that next time someone asks for newDictionary[1] will recieve "Item3" like a content.

Example:

//swap 

string val1 = d[1]; 
string val3 = d[3]; 

d[1] = val3; 
d[3] = val1;

If you need, by the way, some specific order, there is SortedDictionary for that.

International Dictionary of Marketing and Communication, KEY BRITISH ENTERPRISES source and so make possible calculation of the and for interaction in ordering and making payment, simply by pressing numbers on depression of a keyboard key. keyword: word used for searching for items in (equal to one alphabetical character or number), one kilobyte equals 1024  The last argument tells move_to_end() whether to move the item to be the last item in the key sequence (when True) or the first (when False). $ python3 collections_ordereddict_move_to_end.py Before: a A b B c C move_to_end(): a A c C b B move_to_end(last=False): b B a A c C

Ok, Thanks for all the answers, but unfortunately most of what was suggested wouldn't have worked for what I wanted. However this is how I have managed to do this:

public void ReorderDictionary(int oldIndex, int newIndex)
    {
        var oldDictionary = new Dictionary<int, string>();
        oldDictionary.Add(1, "item1");
        oldDictionary.Add(2, "item2");
        oldDictionary.Add(3, "item3");
        oldDictionary.Add(4, "item4");

        var movedItem = oldDictionary[oldIndex];
        oldDictionary.Remove(oldIndex);

        var newDictionary = new Dictionary<int, string>();

        var offset = 0;
        for (var i = 0; i < oldDictionary.Count; i++)
        {
            if (i + 1 == newIndex)
            {
                newDictionary.Add(i, movedItem);
                offset = 1;
            }
            var oldEvent = oldDictionary[oldDictionary.Keys.ElementAt(i)];
            newDictionary.Add(i + offset, oldEvent);
        }
        if (newIndex > oldDictionary.Count)
        {
            newDictionary.Add(oldDictionary.Count + 1, movedItem);
        }
    }

May not be the best way, but unfortunately I have to work with an outdated system. But at least this works :D

OrderedDictionary.Insert(Int32, Object, Object) Method (System , In data communications, a terminal that cannot form its own packets; it is Electrons are injected into the device and are moved along it as the result of It allows the automatic detection of errors in the transcription of classification numbers. In codes, a group of characters, derived from and appended to a data item, that  With the solution of @aKzenT you always have two instances per entry in your dictionary: one for the key and one in the value. With the equals method you only have the instance in dictionary and every instance you use for searching and/or testing is disposed when the appropriate method is finished. – Osiris76 May 16 '11 at 10:50

I tried something in a Console application. Hope this gives you what you are looking for:

public class Program
{
    static void Main(string[] args)
    {
        Dictionary<int, string> dictionary = new Dictionary<int, string>();
        dictionary.Add(1, "item1");
        dictionary.Add(2, "item2");
        dictionary.Add(3, "item3");
        dictionary.Add(4, "item4");

        Dictionary<int, string> sortedDic = ResortDictionary(dictionary, 1, 4);

        foreach (KeyValuePair<int, string> row in sortedDic)
        {
            Console.WriteLine("Key: " + row.Key + "  Value: " + row.Value);
        }

        Console.ReadLine();
    }

    public static Dictionary<int, string> ResortDictionary(Dictionary<int, string> dictionary, int oldOrderNumber, int newOrderNumber)
    {
        string oldOrderNumberValue = dictionary[oldOrderNumber];
        string newOrderNumberValue = dictionary[newOrderNumber];

        dictionary[newOrderNumber] = oldOrderNumberValue;
        dictionary[oldOrderNumber] = newOrderNumberValue;

        return dictionary;
    }
}

Dictionary of Information Technology, For our purposes we can think of this ordering as unpredicatable. The values in a dictionary are accessed with keys, not with indices, so there is no need to The len function also works on dictionaries; it returns the number of key-value pairs: The items method returns both, in the form of a list of tuples — one for each  But only rewrite the key, not the values. so the values keep the same,but replace the keys by their index in the dictionary. stevebaer (Steve Baer) November 16, 2013, 4:56am

If you like to have it a bit shorter use foreach in your reordering method:

private static Dictionary<int, string> ReorderDictionary(Dictionary<int, string> originalDictionary, int newTopItem)
{
    // Initialize ordered dictionary with new top item.
    var reorderedDictionary = new Dictionary<int, string> {{ newTopItem, originalDictionary[newTopItem] }};
    foreach (var item in originalDictionary)
    {
        if (item.Key == newTopItem)
        {
            // Skip the new top item.
            continue;
        }

        reorderedDictionary.Add(item.Key, item.Value);
    }

    return reorderedDictionary;
}

12. Dictionaries, In Dictionary, the key cannot be null, but value can be. In Dictionary, key must The capacity of a Dictionary is the number of elements that Dictionary can hold. If the key is not in the Dictionary<TKey,TValue>, the key and value are added to the dictionary. In contrast, the Add method does not modify existing elements. A key cannot be null, but a value can be, if the value type TValue is a reference type. The C# language uses the this keyword to define the indexers instead of implementing the Item

C# Dictionary with examples, Extend the list by appending all the items in the given list. Return the number of times x appears in the list. For example, this listcomp combines the elements of two lists if they are not equal: It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are  Python: check if key in dictionary using if-in statement. We can directly use the ‘in operator’ with the dictionary to check if a key exist in dictionary or nor. The expression, key in dictionary. Will evaluate to a boolean value and if key exist in dictionary then it will evaluate to True, otherwise False.

5. Data Structures, You can access individual items in a nested dictionary by specifying key in multiple square brackets. D = {'emp1': {'name': 'Bob'  The update() method updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs. The update() method adds element(s) to the dictionary if the key is not in the dictionary.

Python Nested Dictionary, Let's see an efficient method i.e.. Iterate over key value pairs of dictionary using dict.items(). Count – returns the number of items in the Dictionary. Remove – removes a given key from the Dictionary. RemoveAll – removes all items from the Dictionary The following sub shows an example of how you would use these functions

Comments
  • Maybe you need simple list of strings?
  • I'm actually using classes, not strings. I just said string to make it simpler to understand
  • Why not switching values only.
  • I can't just switch a value. For the example I have above if I just switched "item1" would have the order number 3, when it needs to be 2.
  • @Ben. I think in the above example "item1" remains there. Key should remain 2.
  • Yes I get thats what I'd have to do, but how?, I mean I can simply change the order number of one dictionary item key, but how do I change the rest of the items so that I don't end up with multiples of the same key.
  • @Ben: you can not end up with duplicated keys in dictionary, it will raise an exception. I edited my code to clarify what I mean.
  • Swapping won't work. If I just swapped like that then they would all be in the wrong positions. In my exmaple item1 should end up as the second in the list. If I swap, it will become the third in the list when it is item2 that should be third.
  • @Ben: if you care about an order of items, you picked a wrong data-structure for that. dictionary is just a key-value store, order does not matter at all and does not warry you in any way when you are using it. after swap, you will be able to get val3 on request of key1
  • I didn't pick the data structure unfortunately. I just have to work with what I have. But I'm in progress of another way of doing this in a for loop which seems to almost work. Just a few more tweaks needed.
  • I'm not working with a string in the dictionary, I am working with objects, but its just simpler to understand if I say I'm working with a string.