Captain Comic
Captain Comic

Reputation: 16196

Ordered queue with two indices

I need an ordered queue where objects would be ordered by primary and secondary value.

class Object
{
  int PrimaryValue;
  int SecondaryValue;
}

The position of an Object in the queue must be determined by PrimaryValue. Object with higher PrimaryValue must preceed object with lower PrimaryValue. However for two objects with the same PrimaryValue a SecondaryValue must be used to determine precedence. Also I need two functions to get forward iterator GetFirst() and backward iterator GetLast() that would return respective iterators.

Upvotes: 1

Views: 381

Answers (4)

codekaizen
codekaizen

Reputation: 27419

You can just use a List<T>, and call Sort(), however, to do so, instead implement IComparable<T> on your class. Finally, if you want to enumerate in reverse, just call Reverse() on the List<T>.

public class MyObject : IComparable<MyObject>
{
public int First;
public int Second;

public int CompareTo(MyObject other)
{
  if (Equals(this, other))
  {
    return 0;
  }
  if (ReferenceEquals(other, null))
  {
    return 1;
  }
  int first = this.First.CompareTo(other.First);
  if (first != 0)
  {
    return first;
  }
  return this.Second.CompareTo(other.Second);
}
}

Upvotes: 1

AK_
AK_

Reputation: 8099

you just need a SortedList.... and to give it your own copareing thingy...

http://msdn.microsoft.com/en-us/library/ms132323.aspx

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532495

Sounds like what you want is either a PriorityQueue with the priority being a Pair or simply a SortedList with a custom Comparer. Here's an implementation of a PriorityQueue that could be adapted to your needs. Since GetEnumerator() returns an IEnumerable you can use the Reverse() extension method to iterate over it from back to front.

Similarly with the SortedList -- you need only supply a suitable IComparer that performs the comparison you need and use Reverse() for back to front iteration.

Upvotes: 2

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

class Obj : IComparable<Obj>
{
    int PrimaryValue;
    int SecondaryValue;

    public int CompareTo(Obj other)
    {
        if (other == null) throw new ArgumentNullException("other");
        int diff = PrimaryValue - other.PrimaryValue;
        return diff != 0 ? diff : SecondaryValue - other.SecondaryValue;
    }
}

I'm not sure quite what you mean by forward and reverse iterators, which is C++ jargon for concepts that don't really exist in C#. You can always iterate over a collection in the forward direction simply by using foreach (var e in coll) ..., and in reverse by using System.Linq: foreach (var e in coll.Reverse()) ....

Upvotes: 7

Related Questions