6

I have java code that uses SortedMap.tailMap. In my ported code, I have SortedMap = Dictionary<IComparable, value>. I need a way to copy / mimic tailMap in C#.

I've thought something like the following:

myDictionary.Where(p => p.Key.CompareTo(value) >= 0).ToDictionary

This returns a Dictionary, and I need a SortedDictionary returned. I could create a SortedDictionary from the Dictionary, but I feel like there should be a more elegant and perfomant way to do this as it's already sorted.

Another thought was to do something like

var newSD = new SortedDictionary<k,v>();
foreach (var p in oldDictionary.Where(p => p.Key.CompareTo(value) >= 0))
    newSD.Add(p.Key, p.Value);

That should work, I'm not sure how the adding of values in a sorted order will affect timing on the inserts as I build that list.

Any other thoughts?

Prescott
  • 7,312
  • 5
  • 49
  • 70

2 Answers2

1

I've needed this feature a couple of times in the past, and afaik the easiest way to do this is

  1. Create and populate a SortedList<K,V> which is accessible by index (in contrast to SortedDictionary, which is why you cannot use it here)
  2. Use a suitable*) BinarySearch method on IList<K> SortedList.Keys
  3. Access the value via IList<V> SortedList.Values
  4. Wrap 2. and 3. up into an extension method IEnumerable<KeyValuePair<K, V>> Tail(this SortedList<K, V> list, K fromKey, bool inclusive = true)
  5. Post it here as answer so I can copy-and-paste it henceforth I just implemented Head and Tail and appended the code - see below. Also, I added TryGetCeiling/Floor/Higher/LowerValue methods - names derived from Java's NavigableMap, and it's straightforward to add TryGetKey and TryGetEntry for anyone who needs them.

*) Unfortunately, .Net's own implementation works only on Lists, not on ILists. What a waste... Also, be sure to use one that returns ~x in case the item is not found, like the one I linked to.

public static class SortedListEx
{
    public static IEnumerable<KeyValuePair<K, V>> Head<K, V>(
        this SortedList<K, V> list, K toKey, bool inclusive = true)
    {
        https://stackoverflow.com/a/2948872/709537 BinarySearch
        var binarySearchResult = list.Keys.BinarySearch(toKey);
        if (binarySearchResult < 0)
            binarySearchResult = ~binarySearchResult;
        else if (inclusive)
            binarySearchResult++;
        return System.Linq.Enumerable.Take(list, binarySearchResult);
    }

    public static IEnumerable<KeyValuePair<K, V>> Tail<K, V>(
        this SortedList<K, V> list, K fromKey, bool inclusive = true)
    {
        https://stackoverflow.com/a/2948872/709537 BinarySearch
        var binarySearchResult = list.Keys.BinarySearch(fromKey);
        if (binarySearchResult < 0)
            binarySearchResult = ~binarySearchResult;
        else if (!inclusive)
            binarySearchResult++;
        return new ListOffsetEnumerable<K, V>(list, binarySearchResult);
    }

    public static bool TryGetCeilingValue<K, V>(
        this SortedList<K, V> list, K key, out V value)
    {
        var binarySearchResult = list.Keys.BinarySearch(key);
        if (binarySearchResult < 0)
            binarySearchResult = ~binarySearchResult;
        if (binarySearchResult >= list.Count)
        {
            value = default(V);
            return false;
        }
        value = list.Values[binarySearchResult];
        return true;
    }

    public static bool TryGetHigherValue<K, V>(
        this SortedList<K, V> list, K key, out V value)
    {
        var binarySearchResult = list.Keys.BinarySearch(key);
        if (binarySearchResult < 0)
            binarySearchResult = ~binarySearchResult;
        else
            binarySearchResult++;
        if (binarySearchResult >= list.Count)
        {
            value = default(V);
            return false;
        }
        value = list.Values[binarySearchResult];
        return true;
    }

    public static bool TryGetFloorValue<K, V>(
        this SortedList<K, V> list, K key, out V value)
    {
        var binarySearchResult = list.Keys.BinarySearch(key);
        if (binarySearchResult < 0)
            binarySearchResult = ~binarySearchResult;
        else
            binarySearchResult++;
        if (binarySearchResult >= list.Count)
        {
            value = default(V);
            return false;
        }
        value = list.Values[binarySearchResult];
        return true;
    }

    public static bool TryGetLowerValue<K, V>(
        this SortedList<K, V> list, K key, out V value)
    {
        var binarySearchResult = list.Keys.BinarySearch(key);
        if (binarySearchResult < 0)
            binarySearchResult = ~binarySearchResult;
        if (binarySearchResult >= list.Count)
        {
            value = default(V);
            return false;
        }
        value = list.Values[binarySearchResult];
        return true;
    }

    class ListOffsetEnumerable<K, V> : IEnumerable<KeyValuePair<K, V>>
    {
        private readonly SortedList<K, V> _sortedList;
        private readonly int _offset;

        public ListOffsetEnumerable(SortedList<K, V> sortedList, int offset)
        {
            _sortedList = sortedList;
            _offset = offset;
        }

        public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
        {
            return new ListOffsetEnumerator<K, V>(_sortedList, _offset);
        }

        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    }

    class ListOffsetEnumerator<K, V> : IEnumerator<KeyValuePair<K, V>>
    {
        private readonly SortedList<K, V> _sortedList;
        private int _index;

        public ListOffsetEnumerator(SortedList<K, V> sortedList, int offset)
        {
            _sortedList = sortedList;
            _index = offset - 1;
        }

        public bool MoveNext()
        {
            if (_index >= _sortedList.Count)
                return false;
            _index++;
            return _index < _sortedList.Count;
        }

        public KeyValuePair<K, V> Current
        { 
            get
            {
                return new KeyValuePair<K, V>(
                    _sortedList.Keys[_index],
                    _sortedList.Values[_index]);
            }
        }
        object IEnumerator.Current { get { return Current; } }

        public void Dispose() { }
        public void Reset() { throw new NotSupportedException(); }
    }
}

And here's a simple test

SortedList<int, int> l =
    new SortedList<int, int> { { 1, 1 }, { 3, 3 }, { 4, 4 } };
for (int i = 0; i <= 5; i++)
{
    Console.WriteLine("{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( " +i+ ",  true): "
        + string.Join(", ", l.Head(i, true)));
    Console.WriteLine("{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( " +i+ ", false): "
        + string.Join(", ", l.Head(i, false)));
}
for (int i = 0; i <= 5; i++)
{
    Console.WriteLine("{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( " +i+ ",  true): "
        + string.Join(", ", l.Tail(i, true)));
    Console.WriteLine("{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( " +i+ ", false): "
        + string.Join(", ", l.Tail(i, false)));
}

which prints the following:

{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 0,  true):
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 0, false):
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 1,  true): [1, 1]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 1, false):
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 2,  true): [1, 1]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 2, false): [1, 1]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 3,  true): [1, 1], [3, 3]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 3, false): [1, 1]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 4,  true): [1, 1], [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 4, false): [1, 1], [3, 3]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 5,  true): [1, 1], [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Head( 5, false): [1, 1], [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 0,  true): [1, 1], [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 0, false): [1, 1], [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 1,  true): [1, 1], [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 1, false): [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 2,  true): [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 2, false): [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 3,  true): [3, 3], [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 3, false): [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 4,  true): [4, 4]
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 4, false):
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 5,  true):
{ { 1, 1 }, { 3, 3 }, { 4, 4 } }.Tail( 5, false):
Evgeniy Berezovsky
  • 18,571
  • 13
  • 82
  • 156
0

TreeMap has a tail map. Is that what you are actually looking for?

fodon
  • 4,565
  • 12
  • 44
  • 58
  • Apologies, I'm looking for the reverse - a tailMap in C# (My understanding is TreeMap => SortedDictionary in C#, but alas, SortedDictionary appears to have no tailMap – Prescott Sep 27 '14 at 21:27