473,498 Members | 1,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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];}
index1.Bubblesort();
}
}

Sep 10 '07 #1
3 4375
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.

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

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,
rhs.x);});

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

Marc

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.

Jon

Sep 10 '07 #4

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

Similar topics

1
2187
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...
29
2589
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...
6
6078
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...
0
2487
by: metaperl | last post by:
A Comparison of Python Class Objects and Init Files for Program Configuration ============================================================================= Terrence Brannon bauhaus@metaperl.com...
16
2727
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:...
10
5205
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...
0
2551
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...
5
2629
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...
3
3308
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. ...
0
7124
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6998
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7163
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6884
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7375
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5460
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4904
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
1
651
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
287
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.