473,468 Members | 1,370 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Comparing objects

Hello,

I've to implement a IComparer in order to sort an arraylist.
I've used reflection to get the object I need to sort, at the moment
I'm using the following piece of code:

public int Compare(object x, object y)
{
int i = 0;

object c = getIvar(x, listaOrdinamento[0].ToString());
object d = getIvar(y, listaOrdinamento[0].ToString());

i = c.ToString().CompareTo(d.ToString());

return i;
}

is there better way of doing that?
Have I to check the type of c and d and do the compare based on type?
or does the .ToString() cover all the cases?

Thanks

Bests

Paolo

May 15 '06 #1
5 2190

Look at this idea:

I'm not sure if it'll help or not:


using System;
using System.Collections;
namespace MyApplication.Comparers
{
internal sealed class EmployeeComparer : IComparer
{
private EmployeeSortColumns m_sortValue = EmployeeSortColumns.None ;

public enum EmployeeSortColumns
{
None = 0 , LastName = 1 , FirstName = 2 , LastNameAndFirstName = 3
}

public EmployeeComparer(EmployeeSortColumns sortValue)
{
m_sortValue = sortValue;
}

public int Compare(object x,object y)
{
switch(m_sortValue)
{

case EmployeeSortColumns.None :
return 0;
case EmployeeSortColumns.FirstName :

return ((Employee)x).FirstName .CompareTo(((Employee )y).FirstName );
//break;
case EmployeeSortColumns.LastName :
return ((Employee)x).LastName.CompareTo(((Employee )y).LastName );

case LastNameAndFirstName :

string xValue = ((Employee)x).LastName + ((Employee)x).FirstName;
string yValue = ((Employee)y).LastName + ((Employee)y).FirstName;

return xValue.CompareTo(yValue);

default:
return ((Employee)x).LastName .CompareTo(((Employee )y).LastName );
// break;
}
}
}
}




<pa***********@gmail.com> wrote in message
news:11*********************@j55g2000cwa.googlegro ups.com...
Hello,

I've to implement a IComparer in order to sort an arraylist.
I've used reflection to get the object I need to sort, at the moment
I'm using the following piece of code:

public int Compare(object x, object y)
{
int i = 0;

object c = getIvar(x, listaOrdinamento[0].ToString());
object d = getIvar(y, listaOrdinamento[0].ToString());

i = c.ToString().CompareTo(d.ToString());

return i;
}

is there better way of doing that?
Have I to check the type of c and d and do the compare based on type?
or does the .ToString() cover all the cases?

Thanks

Bests

Paolo

May 15 '06 #2
Hi,

pa***********@gmail.com schrieb:
Hello,

I've to implement a IComparer in order to sort an arraylist.
I've used reflection to get the object I need to sort, at the moment
I'm using the following piece of code:

public int Compare(object x, object y)
{
int i = 0;

object c = getIvar(x, listaOrdinamento[0].ToString());
object d = getIvar(y, listaOrdinamento[0].ToString());

i = c.ToString().CompareTo(d.ToString());

return i;
}

is there better way of doing that?
Have I to check the type of c and d and do the compare based on type?
or does the .ToString() cover all the cases?

Thanks

Bests

Paolo


that depends on the objects you want to compare. Are they of the same
type or base on the same type, other that Object? If so, just make this
type implement the IComparable interface and compare the two objects.

For comparison, you should know, by what attribute you want to compare.
Is it something like a name, a size, a whatever? The ToString member is
not very good for comparison. I'm not sure, what the default output for
Object.ToString actually is, but I would not use it for a comparison.
Most probably you will end up in an unsatisfying sorting.

Tobi
May 15 '06 #3
Thanks for your fast answer,

sloan : I've tought about switching, but there's one more problem,
I've to sort based on an arraylist of 3 element (multiple-sort array)
and I need it to be as much generic as possible since it will be
applied to different object, not only to one. I'll pass the sort-rule
ArrayList externally.

Tobias : the comparison is on item of the same type, for example I may
have an arraylist of Employer where once I order with LastName,
FirstName, BirthDate, last time with a different order

Thanks a lot guys!

May 15 '06 #4
pa***********@gmail.com schrieb:
Thanks for your fast answer,

sloan : I've tought about switching, but there's one more problem,
I've to sort based on an arraylist of 3 element (multiple-sort array)
and I need it to be as much generic as possible since it will be
applied to different object, not only to one. I'll pass the sort-rule
ArrayList externally.

Tobias : the comparison is on item of the same type, for example I may
have an arraylist of Employer where once I order with LastName,
FirstName, BirthDate, last time with a different order
Then this is easy. Just let let the type Employer implement the
IComparable interface:

<code>

class Employer : IComparable {
// ...
public int CompareTo(object obj) {
// check not null and same type
if (obj == null || !(obj is Employer)) {
throw ArgumentException();
}

// compare by Name
return this.Name.CompareTo(((Employer)obj).Name);
}
}

</code>

You should adjust the comparison to your requirements ;)

If you want to sort the list of Employers (List employerList), just call
employerList.Sort();
The method will automatically use the Employer.CompareTo member for
comparison.

Thanks a lot guys!

May 15 '06 #5
class FirstNameAscending : IComparer
{
public Compare(object x, object y)
{
Employer lhs = x as Employer;
Employer rhs = y as Employer;
// Add error handling for if either lhs or rhs is null here.
return lhs.FirstName.CompareTo(rhs.FirstName);
}
}

ArrayList Employers = ......
IComparer sortby = null;
switch (....)
{
case 1: sortby = new FirstNameAscending(); break;
case 5: sortby = new LastNameDescending(); break;
// etc.
}

Employers.Sort(sortby);

I'm not sure what you mean by "arraylist of 3 element (multiple-sort
array) ".
I'm gonna guess that you be getting something like:
string[] SoryBy = {"LastName" , "FirstName", "BirthDate"}

This complicates it a bit, but the basic principle above remains. You
do not want to decide how you will be sorting the items inside the
Compare. That should be done *once* beforehand.

class class FirstNameAscending : IComparer
{
IComparer otherwise;
public FirstNameAscending( IComparer pComparer)
{ otherwise = pComparer; }

public int Compare(object x, object y)
{
Employer lhs = x as Employer;
Employer rhs = y as Employer;
int cmp = lhs.FirstName.CompareTo(rhs.FirstName);
if (cmp != 0 || otherwise == null)
return cmp;
else
return otherwise.Compare(x, y);
}

IComparer sortby = new LastNameAscending(new
FirstNameAscending(new BirthDateDescending(null)))
employers.Sort(sortby);

or more generally:
string[] SortByStr = {"LastName" , "FirstName", "BirthDate"}
IComparer sortby = null;
for(i=SortByStr.Length-1; i>=0; --i)
{
switch (SortByStr[i])
{
case "FirstName":
sortby = new FirstNameAscending(sortby);
break;
case "LastName":
sortby = new LastNameAscending(sortby);
break;
// etc.
}
}
employers.Sort(sortby);

May 15 '06 #6

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

Similar topics

19
by: Dennis | last post by:
I have a public variable in a class of type color declared as follows: public mycolor as color = color.Empty I want to check to see if the user has specified a color like; if mycolor =...
3
by: Mark Denardo | last post by:
Hi I have an app that has a number of textboxes (richtextboxes to be exact) that get created dynamically and I add a few at a time to panel controls (so I can flip a group in and out when I want). ...
5
by: ma740988 | last post by:
There's a need for me to move around at specified offsets within memory. As as a result - long story short - unsigned char* is the type of choice. At issue: Consider the case ( test code ) where...
20
by: Bill Pursell | last post by:
This question involves code relying on mmap, and thus is not maximally portable. Undoubtedly, many will complain that my question is not topical... I have two pointers, the first of which is...
25
by: J Caesar | last post by:
In C you can compare two pointers, p<q, as long as they come from the same array or the same malloc()ated block. Otherwise you can't. What I'd like to do is write a function int comparable(void...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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
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,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.