Nemo
Nemo

Reputation: 4741

Comparing custom types

I am implementing a generic PriorityQueue in C# as part of homework. The items are stored in an array.

class PQueue<T> : IPQueue<T>
{
    T[] items;
    //..
}

How can I compare two items. I guess the type with which PQueue is instantiated has to implement IComparable/IComparer. If so, how can I compare two elements in items?

What is the elegant way to design this.

Upvotes: 3

Views: 202

Answers (3)

radarbob
radarbob

Reputation: 5101

First, your custom type (T) must have a sort order

Either T is a built in number type like int, double, etc. that has a "natural" sort order; or you must define/code it into your custom class.

Perhaps there is some class property or combination of properties that are one of those built in types that you can use to decide sort order for your custom class.

Alphabet characters have "natural" sort order. Keep in mind that the sort order of upper & lower cases of a given letter are not sequential. When it comes to strings, if Upper/lower case is not essential (for sorting purposes) convert strings to lower (or upper, does not really matter which) before comparing.

Any Enumerations you write have sort order because they are fundamentally integers.

CompareTo() defines sort order for your custom class

This method is the "rubber meets the road" grunt code that decides order of the two objects being compared. How it works is something you must work out.

About your IPQueues Class

Array as the internal collection does not seem like a good idea as the array size is fixed. .NET has a Queue class; could that work for you?

Upvotes: 0

Cameron
Cameron

Reputation: 98886

You're probably looking for generic constraints that let you specify that T must implement IComparable:

class PQueue<T> : IPQueue<T> where T : IComparable<T>
{
    // ...
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727107

First, you need to tell C# that <T> implements IComparable<T>

class PQueue<T> : IPQueue<T> where T : IComparable<T> {
    T[] items;
    //..
}

Now you can compare individual items, like this:

var cmp = items[i].CompareTo(items[j]);
if (cmp < 0) {
    // items[i] is less than items[j]
} else if (cmp > 0) {
    // items[i] is greater than items[j]
} else {
    // Items are equal
}

Upvotes: 3

Related Questions