简体   繁体   中英

.NET equivalent of Java's TreeSet operations tailSet and headSet?

I'm trying to use .NET 4's SortedSet<T> collection. It seems to have everything I need minus a couple things.

Q : I want to be able to fetch all elements lower or higher in comparison to a given value. In Java's TreeSet , there are methods named tailSet and headSet , which perform these operations. I'd like to be able to do the same with SortedSet<T> . The closest I can find is GetViewBetween . However, what if I wanted to use SortedSet with string ? There is no max value of string that I know of, yet I need to give the method an upper and lower bounds.

How could I mimic the behavior of tailSet and headSet using SortedSet ? Considering the implementation of SortedSet , I'd think that these would be very easy methods to implement.

Thanks!

I believe you can emulate them like this: sortedSet.GetViewBetween(start, sortedSet.Max) sortedSet.GetViewBetween(sortedSet.Min, end)

static SortedSet<T> TailSet<T>(this SortedSet<T> set, T start)
{
    return set.GetViewBetween(start, set.Max);
}

static SortedSet<T> HeadSet<T>(this SortedSet<T> set, T end)
{
    return set.GetViewBetween(set.Min, end);
}

Alternately, you can use LINQ:

static SortedSet<T> TailSet<T>(this SortedSet<T> set, T start)
{
    return new SortedSet<T>(set.SkipWhile(
        x => set.Comparer.Compare(x, start) < 0));
}

static SortedSet<T> HeadSet<T>(this SortedSet<T> set, T end)
{
    return new SortedSet<T>(set.TakeWhile(
        x => set.Comparer.Compare(x, end) < 0));
}

The primary difference is that GetViewBetween gives you an object with a pointer to the original set, so any changes in the original set can be reflected in the copies. The LINQ version creates a new set based on the contents of the original, giving copies that don't track each other. Of course, you could also do something like new SortedSet<T>(set.GetViewBetween(set.Min, end)) to get the cloning behavior.

I think a little LINQ may solve the problem:

        var sortedSet = new SortedSet<string>();
        sortedSet.Add("Santiago");
        sortedSet.Add("Alejandra");
        sortedSet.Add("Carolina");
        sortedSet.Add("Sebastián");

        var head = sortedSet.Where(s => string.Compare(s, "Carolina") < 0);
        var tail = sortedSet.Where(s => string.Compare(s, "Carolina") >= 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM