Faisal Shahid
Faisal Shahid

Reputation: 3

How can i make any element first of Idictionary object in C# by key?

I have object type of IDictionary and i want to custom sort of object items e.g

 IDictionary<string, object> animalObjects = new Dictionary<string, object>()

animalObjects = {                                       
Monkey,SomeValue,
Cat,SomeValue,
Tiger,SomeValue,
Zebra,SomeValue 
}

Now i want to set "Tiger" as first element of object.

Upvotes: 0

Views: 42

Answers (1)

SomeBody
SomeBody

Reputation: 8743

A dictionary has no order. If you iterate over it, there is no guarantee that you will receive the entries in a certain order. If you need a certain order, you have to sort it by yourself. You can use LINQ for this:

foreach(var entry in animalObjects.OrderBy(x => x.Key != "Tiger"))
{
    Console.WriteLine(entry.Key + " " + entry.Value);
}

Online demo: https://dotnetfiddle.net/dwKtg4

Note that you will need to sort the dictionary every time you iterate it. If you want to iterate the dictionary very often and it has a lot of entries, this is not a smart solution. In that case, you should check whether a dictionary is the right data structure for your case. Maybe a List<(string,object)> is better in that case.

Upvotes: 0

Related Questions