473,466 Members | 1,538 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

sorting

Hi

say I have a list of Person objects, which I want to sort. But I don't just
want to sort by "name" say, but by several fields in the Person object.
Maybe 1st priority by height, 2nd priority by weight, and 3rd priority by
age.

A Person object has many attributes though, and I want to be able to select
between all of the fields for sorting (with 1st, 2nd, 3rd priority).
What would be a good approach?

Thanks,
Peter
May 15 '06 #1
7 1526
"Peter Kirk" <pk@alpha-solutions.dk> wrote:
say I have a list of Person objects, which I want to sort. But I don't just
want to sort by "name" say, but by several fields in the Person object.
Maybe 1st priority by height, 2nd priority by weight, and 3rd priority by
age.

What would be a good approach?


Write a static method (following the signature of the Comparison<T>
delegate where T is Person) which accepts two Person objects and returns
an integer. The return value should be less than zero if the first
person comes first, equal to zero if the two persons compare equally,
and greater than zero if the second person comes first. When writing the
method, compare the heights first, and only continue to the weight if
the heights are equal, and so on.

Pass this static method to List<T>.Sort().

If you want a fully general solution, you can get it by playing with
reflection, but get the hard-coded solution working first. After that,
it's relatively easy to use reflection to access the values of a given
property on a given object, and write a loop to perform the comparisons
for each property in turn.

-- Barry
May 15 '06 #2
Peter Kirk wrote:
Hi

say I have a list of Person objects, which I want to sort. But I don't just
want to sort by "name" say, but by several fields in the Person object.
Maybe 1st priority by height, 2nd priority by weight, and 3rd priority by
age.

A Person object has many attributes though, and I want to be able to select
between all of the fields for sorting (with 1st, 2nd, 3rd priority).
What would be a good approach?


Most ways of sorting have an overload that accepts an IComparer object
(*), which gets asked to compare pairs of objects and return the order
they should sort in. You could define a PersonComparer class that
implements IComparer - give this class a property or properties that
tell it how to sort Persons, then when you want to sort, create an
appropriate PersonComparer and give it to the sort method.

* eg
<http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemArrayClassSortTopic3.asp>
= <http://tinyurl.com/odry5>

--
Larry Lard
Replies to group please

May 15 '06 #3


one trick is to string together the string properties, and sort on them.

I'm writing this mostly from memory, so hopefully its nearly all correct.
but you should see the idea.

( case LastNameAndFirstName is what I'm talking about).
At the least, you'll see how to write 1 comparer for multiple properites ..
using the Enum thing.

...
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;
}
}
}
}


...

Other comments:

While I'm usually in favor of using strong objects and collections, this is
one area where the strongly typed dataset is helpful, since
it has a .Select ( filter, sortby ) method.

MyStrongDS.EmpTable.Select ("" , "LastName , FirstName DESC , City");

something like that.

"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
Hi

say I have a list of Person objects, which I want to sort. But I don't just want to sort by "name" say, but by several fields in the Person object.
Maybe 1st priority by height, 2nd priority by weight, and 3rd priority by
age.

A Person object has many attributes though, and I want to be able to select between all of the fields for sorting (with 1st, 2nd, 3rd priority).
What would be a good approach?

Thanks,
Peter

May 15 '06 #4

sloan wrote:
one trick is to string together the string properties, and sort on them.


Be careful when using this method. Some data types will not be sorted
correctly. One example off the top of my head is DateTime.

Brian

May 15 '06 #5
Yeah, I concur.

I think maybe that's why sometimes I switch out to the StronglyTyped
DataSets...
When I need advanced sorting features.....

And I dont' have in production any of these "string togethers", except maybe
one LastName/First thing.

But the option exists........ for certain situations.

Thanks for voicing the "gotcha" on that method.


"Brian Gideon" <br*********@yahoo.com> wrote in message
news:11*********************@g10g2000cwb.googlegro ups.com...

sloan wrote:
one trick is to string together the string properties, and sort on them.


Be careful when using this method. Some data types will not be sorted
correctly. One example off the top of my head is DateTime.

Brian

May 15 '06 #6
Yeah, just recently I used that method as a quick get-r-done
implementation and marked the code with a TODO comment to remind me to
go back in and change it. Well, I forgot to change it and I missed the
problem during testing because the incorrect order only occurred in
less than 1% of the scenarios. I was really frustrated with myself for
not doing it right the first time.

Brian

sloan wrote:
Yeah, I concur.

I think maybe that's why sometimes I switch out to the StronglyTyped
DataSets...
When I need advanced sorting features.....

And I dont' have in production any of these "string togethers", except maybe
one LastName/First thing.

But the option exists........ for certain situations.

Thanks for voicing the "gotcha" on that method.

"Brian Gideon" <br*********@yahoo.com> wrote in message
news:11*********************@g10g2000cwb.googlegro ups.com...

sloan wrote:
one trick is to string together the string properties, and sort on them.


Be careful when using this method. Some data types will not be sorted
correctly. One example off the top of my head is DateTime.

Brian


May 15 '06 #7
I just wrote some code to answer a similar question in the "Comparing
Object" thread of this newsgroup:

http://groups.google.com/group/micro...a5d6675f20ed0a

May 15 '06 #8

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

Similar topics

4
by: dont bother | last post by:
This is really driving me crazy. I have a dictionary feature_vectors{}. I try to sort its keys using #apply sorting on feature_vectors sorted_feature_vector=feature_vectors.keys()...
0
by: ck388 | last post by:
For some reason when I enable the callback feature of the gridview I still get a page refresh, that is it seems like there is a postback that occurs, not a callback which is just supposed to update...
7
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) ...
19
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to...
10
by: Sjaakie | last post by:
Hi, I'm, what it turns out to be, fooling around with 3-tier design. At several websites people get really enthusiastic about using custom dataobjects instead of datasets/-tables. While trying to...
4
by: Ambica Jain | last post by:
Hi, I want custom sorting on some of the columns in the datagrid. And i am able to do the same by overriding MouseDown event. However, i need to rebind my datatable to reflect the changes in...
7
by: Kamal | last post by:
Hello all, I have a very simple html table with collapsible rows and sorting capabilities. The collapsible row is hidden with css rule (display:none). When one clicks in the left of the...
1
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar...
5
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The...
5
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums...
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
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
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.