472,995 Members | 1,579 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,995 software developers and data experts.

Value comparison in sorting a generic list class

I have created a small program that illustrates the problem. I would know how
to address the fields that I want to sort on in the greaterThan comparison.
Anybody who knows??
using System;

class Program
public List<itemitList, index1;

public class List<T>
{ T[] items;

public List(int capacity)
{ items = new T[capacity];

public T this[int index]
{ get { return items[index]; }
set { items[index] = value; }

static bool greaterThan(T a, T b)
{ return (a.x b.x); // 1. How to do this?
} // 2. And a flexible assignment of x or y

public void swap(int i, int j)
{ T temp = this[i];
this[i] = this[j];
this[j] = temp;

public void Bubblesort()
{ Boolean noswap = false;
while (!noswap)
{ noswap = true;
for (int i = 0; i < this.items.Length - 1; i++)
{ if (greaterThan(this[i], this[i + 1]))
{ this.swap(i, i + 1);
noswap = false;

public class item //struct or class whatever
{ public double x, y;
public item(double x, double y)
{ this.x = x;
this.y = y;
public double fieldx() {
return this.x;

static void Main(string[] args)
{ List<itemitList = new List<item>(99);
Random RandObj = new Random();
for (int i = 0; i < 99; i++)
{ itList[i] = new item(RandObj.NextDouble() * 100,
RandObj.NextDouble() * 100);
List<itemindex1 = new List<item>(99);
for (int i=0;i<99;i++){index1[i]=itList[i];}

Sep 10 '07 #1
3 4353
GB wrote:
I have created a small program that illustrates the problem. I would know how
to address the fields that I want to sort on in the greaterThan comparison.
static bool greaterThan(T a, T b)
{ return (a.x b.x); // 1. How to do this?
} // 2. And a flexible assignment of x or y
The answer depends on what exactly you're trying to achieve.

The most straightforward answer is to constrain the class T to implement
IComparable, and then use the Compare method. In the
IComparable.Compare method, that's where you'd write the actual
comparison using the specific fields. This is how existing .NET classes
do it (well, it's one way they offer...you can often also instead
implement an IComparer class that does the same thing, but doesn't
require changing the compared class itself).

But your question implies that you really want the generic class to know
about the fields in question. AFAIK, you can't do that exactly, not
with fields. However, you could create a custom interface that defines
a property to be used in the comparison, and then again using a
constraint for the generic class's type, require T to implement that
interface. Then in the greaterThan() method you can use the property
you declared in the interface.

If the above doesn't answer the question, you may want to elaborate on
what behavior exactly you're trying to achieve. Your question is asking
for a specific implementation, but it may be that talking about what the
actual end goal is would be more productive.

Sep 10 '07 #2
First - why write your own List<T- is this just for academic

However, the simplest (and most appropriate) approach would be for you
Sort() [or BubbleSort()] method to accept either an IComparer<T>, or a
Comparison<T>. This allows the external caller to control the sort
(i.e. greaterThan is owned by the caller, not the list). A similar
example is here: http://msdn2.microsoft.com/en-us/library/w56d4y5z.aspx

This also allows for very tidy inline usage - i.e.

myList.Sort(delegate(Item lhs, Item rhs) {return int.Compare(lhs.x,

this will probably get even tidier in 3.5 with lambda expressions.


Sep 10 '07 #3
On Sep 10, 10:44 am, GB <G...@discussions.microsoft.comwrote:
I have created a small program that illustrates the problem. I would know how
to address the fields that I want to sort on in the greaterThan comparison.
Anybody who knows??
Either add a constraint on T that it must implement IComparable<T>, or
use Comparer<T>.Default.Compare.


Sep 10 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: David Pratt | last post by:
I have been using the following for sorting a list of dictionaries. This works but only provides sorting on a single key. I am wanting to extend this with a better comparison expression so that it...
by: Steven D'Aprano | last post by:
Playing around with comparisons of functions (don't ask), I discovered an interesting bit of unintuitive behaviour: >>> (lambda y: y) < (lambda y: y) False Do the comparison again and things...
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or...
by: metaperl | last post by:
A Comparison of Python Class Objects and Init Files for Program Configuration ============================================================================= Terrence Brannon bauhaus@metaperl.com...
by: Kittyhawk | last post by:
I would like to sort an Arraylist of objects on multiple properties. For instance, I have a Sort Index property and an ID property (both integers). So, the results of my sort would look like this:...
by: Wing Siu | last post by:
Dear All I would like to develop a generic class sorting function. Currently, when I need sort a collection of user class, for example: Person, Exhibition, Country I need implement a comparer...
by: SvenMathijssen | last post by:
Hi, I've been wrestling with a problem for some time that ought to be fairly simple, but turns out to be very difficult for me to solve. Maybe someone here knows the answer. What I try to do is...
by: MightyTater | last post by:
Hey all, I am very new to python, and not usually a programmer. Have mercy, please :) I am comparing road address ranges to find inconsistencies. Some roads are much longer than others and are...
by: Greg D | last post by:
Hi all, I'm trying to sort an array of objects within an object. Included is a dumbed down example so that we can get at the meat of the issue without worrying about complexity or validation. ...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.