Reverse Sorted Dictionary in .NET
The SortedDictionary itself doesn't support backward iteration, but you have several possibilities to achieve the same effect.
Use
.Reverse
-Method (Linq). (This will have to pre-compute the whole dictionary output but is the simplest solution)var Rand = new Random();
var Dict = new SortedDictionary<int, string>();
for (int i = 1; i <= 10; ++i) {
var newItem = Rand.Next(1, 100);
Dict.Add(newItem, (newItem * newItem).ToString());
}
foreach (var x in Dict.Reverse()) {
Console.WriteLine("{0} -> {1}", x.Key, x.Value);
}Make the dictionary sort in descending order.
class DescendingComparer<T> : IComparer<T> where T : IComparable<T> {
public int Compare(T x, T y) {
return y.CompareTo(x);
}
}
// ...
var Dict = new SortedDictionary<int, string>(new DescendingComparer<int>());Use
SortedList<TKey, TValue>
instead. The performance is not as good as the dictionary's (O(n) instead of O(logn)), but you have random-access at the elements like in arrays. When you use the generic IDictionary-Interface, you won't have to change the rest of your code.
Edit :: Iterating on SortedLists
You just access the elements by index!
var Rand = new Random();
var Dict = new SortedList<int, string>();
for (int i = 1; i <= 10; ++i) {
var newItem = Rand.Next(1, 100);
Dict.Add(newItem, (newItem * newItem).ToString());
}
// Reverse for loop (forr + tab)
for (int i = Dict.Count - 1; i >= 0; --i) {
Console.WriteLine("{0} -> {1}", Dict.Keys[i], Dict.Values[i]);
}
SortedDictionary in reverse order of keys
You can give SortedDictionary
an IComparer<TKey>
on construction. You just need to provide one which reverses the order. For example:
public sealed class ReverseComparer<T> : IComparer<T>
{
private readonly IComparer<T> original;
public ReverseComparer(IComparer<T> original)
{
// TODO: Validation
this.original = original;
}
public int Compare(T left, T right)
{
return original.Compare(right, left);
}
}
Then:
var dictionary = new SortedDictionary<int, string>(
new ReverseComparer<int>(Comparer<int>.Default));
Reversed Sorted Dictionary?
You can create a reverse comparer quite easily:
public sealed class ReverseComparer<T> : IComparer<T> {
private readonly IComparer<T> inner;
public ReverseComparer() : this(null) { }
public ReverseComparer(IComparer<T> inner) {
this.inner = inner ?? Comparer<T>.Default;
}
int IComparer<T>.Compare(T x, T y) { return inner.Compare(y, x); }
}
Now pass that into the constructor for the dictionary:
var dict = new SortedDictionary<TPriority, Queue<TValue>>(
new ReverseComparer<TPriority>());
How to sort the keys of a dictionary in reverse order using VB.NET?
You can use LINQ to solve this easily:
Dim dicItems As New Dictionary(Of Integer, String)
With dicItems
.Add(1, "cat")
.Add(2, "dog")
.Add(3, "bird")
End With
dim query = from item in dicItems
order by item.Key descending
select item
If you want, you can also use the Lambda syntax:
Dim query = dicItems.OrderByDescending(Function(item) item.Key)
Reversed Sorted Dictionary?
You can create a reverse comparer quite easily:
public sealed class ReverseComparer<T> : IComparer<T> {
private readonly IComparer<T> inner;
public ReverseComparer() : this(null) { }
public ReverseComparer(IComparer<T> inner) {
this.inner = inner ?? Comparer<T>.Default;
}
int IComparer<T>.Compare(T x, T y) { return inner.Compare(y, x); }
}
Now pass that into the constructor for the dictionary:
var dict = new SortedDictionary<TPriority, Queue<TValue>>(
new ReverseComparer<TPriority>());
How to sort Dictionary on keys in c#
var dict = new Dictionary<int, string>(){
{1, "a"},
{3, "c"},
{2, "b"}
};
foreach (var k in dict.OrderByDescending(x => x.Key))
{
Console.WriteLine(k);
}
how to do a dictionary reverse lookup
Basically, You can use LINQ
and get the Key
like this, without reversing anything:
var key = dictionary.FirstOrDefault(x => x.Value == "ab").Key;
If you really want to reverse your Dictionary, you can use an extension method like this:
public static Dictionary<TValue, TKey> Reverse<TKey, TValue>(this IDictionary<TKey, TValue> source)
{
var dictionary = new Dictionary<TValue, TKey>();
foreach (var entry in source)
{
if(!dictionary.ContainsKey(entry.Value))
dictionary.Add(entry.Value, entry.Key);
}
return dictionary;
}
Then you can use it like this:
var reversedDictionary = dictionary.Reverse();
var key = reversedDictionary["ab"];
Note: if you have duplicate values then this method will add the first Value
and ignore the others.
how to iterate a dictionarystring,string in reverse order(from last to first) in C#?
Just use the Linq extension method Reverse
e.g.
foreach( var item in d.Reverse())
{
...
}
How to reverse the index in array of dictionaries?
You shouldn't assume dictionaries are ordered. They aren't.
If you want to have an array that is ordered, you should use a SortedDictionary
. You can also reverse the order in there if you want to. You should use a custom comparer for that (altered from here):
class DescendedStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
int ascendingResult = Comparer<string>.Default.Compare(x, y);
// turn the result around
return 0 - ascendingResult;
}
}
//
SortedDictionary<string, string> test
= new SortedDictionary<string, string>(new DescendedDateComparer());
You can iterate over it with foreach
for example. The results will be ordered descending.
Reverse key and value in dictionary
This is a fairly simple LINQ expression:
var res = dict
.GroupBy(p => p.Value)
.ToDictionary(g => g.Key, g => g.Select(pp => pp.Key).ToList());
First, you group by the value. This creates groups with strings as keys, and KeyValuePair<int,string>
as its items.
Then you convert the groups to a dictionary by using groups's key for the dictionary key, and "flattening" the keys of the original dictionary into a list with ToList()
.
Related Topics
Newtonsoft.JSON Assembly Package Version Mismatch
How to Use Multi Color in Richtextbox
Programmatically Getting the Last Filled Excel Row Using C#
How to Change Pixel Color of an Image in C#.Net
Multiple Identities in ASP.NET Core 2.0
Process.Start to Open an Url, Getting an Exception
Create Http Post Request and Receive Response Using C# Console Application
How to Display Progress During a Busy Loop
Perform Screen-Scape of Webbrowser Control in Thread
Wpf Clickonce Dpi Awareness Per-Monitor V2
Datagrid Column Width Doesn't Auto-Update
How to Remove Numbers from String Using Regex.Replace
Output Console.Writeline from Wpf Windows Applications to Actual Console
Applying % Number Format to a Cell Value Using Openxml
Print HTML Document from Windows Service Without Print Dialog
Usage of Ioc Containers; Specifically Windsor