Java TreeMap equivalent in C#?
Asked Answered
D

4

25

Most places I've consulted say to use SortedList, but the problem is that the program I'm porting actually uses duplicate keys (differentiated by order), which is permissible with TreeMap, but not SortedList.

Any advice?

Disbursement answered 25/1, 2009 at 17:28 Comment(0)
T
22

Does SortedDictionary class help?

Tower answered 18/11, 2013 at 13:35 Comment(3)
The SortedDictionary will not work because it throws ArgumentException on duplicate keys. As the OP said, duplicate keys will be present.Recapture
Just use SortedDictionary<of TKey, of TValue>.Item[TKey] property setter, it replaces value if the key is already in a tree.Paedogenesis
@Leonid Vasilev: That doesn't work either, because then you'll have one item too few in the dictionary, which can cause malfunctions. e.g. happend to me when translating github.com/matsim-up/freight-sa/blob/master/src/main/java/org/… to C#Partridgeberry
S
4

Another great implementation of a Red Black Tree in .NET can be found here: http://www.itu.dk/research/c5/

Sadyesaechao answered 27/1, 2009 at 4:18 Comment(0)
A
1

I don't think C# has one natively. However there are plenty of examples of Red-Black implementations out there. Here is one:-

http://www.codeproject.com/KB/recipes/redblackcs.aspx

Andalusite answered 25/1, 2009 at 17:34 Comment(0)
J
0

Generally use the sorted set

public class ItemComparer : IComparer<int[]>
{
    public int Compare(int[] item1, int[] item2)
    {
        if (item1[0] != item2[0]) return item1[0].CompareTo(item2[0]);
        return item1[1].CompareTo(item2[1]);
    }
}
var s = new SortedSet<int[]>(new ItemComparer());
Jamaaljamaica answered 15/9, 2020 at 11:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.