473,746 Members | 2,268 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

IComparer, Compare, CompareTo for multiple comparisons for Sort inArray and List

This is an example of using multiple comparison criteria for IComparer/
Compare/CompareTo for List<and Array.

Adapted from David Hayden's tutorial found on the net, but he used
ArrayList so the format was different.

Basically you can sort a class having members LastName (string),
FirstName (string) and Age (int) according to whether you want to sort
by Last Name, First Name or Age, using the .Sort function

Question for the group: a suggestion in Albahari C#3 in a Nutshell
says you can, as an alternative to calling Sort, use LINQ's "OrderBy"
and "ThenBy" operators. Unlike Array.Sort or List.Sort, the LINQ
operators don't alter the original array or list, but instead emit the
sorted result in a fresh IEnumerable<Tse quence.

Any idea on how this can be done here? Remember, the
"strings" (LastName, FirstName) and "int" (Age) are stored inside a
class here, so it might be hard to do, since it seems to me LINQ
queries require something like string [] FirstName = {"Tom", "Dick",
"Harry"}; outside a class, rather than having the variables inside a
class as here.

If there's an easy way to use Linq, please post the complete code
otherwise just a hint or pseudocode.

Thanks

RL
// September 30, 2008
//adapted from David Hayden [MVP C#] tutorial on net
// in Hayden an ArrayList rather than a List was used
// so the format was slightly different than here

using System;
using System.Collecti ons.Generic;
using System.Linq;
using System.Text;

namespace console1
{
class Program
{
static void Main(string[] args)
{

List<PersonPers onList = new List<Person>();
PersonList.Add( new Person("ray", "lopez", 38));
PersonList.Add( new Person("zoe", "smith", 28));
PersonList.Add( new Person("nue", "mather", 58));

PersonComparer myPersonCompare r = new PersonComparer( );

myPersonCompare r.ComparisonMet hod =
PersonComparer. ComparisonType. Age;
PersonList.Sort (myPersonCompar er);
foreach (Person p in PersonList) Console.Write(p .LastName
+ "|");
// works, sort by age

Console.WriteLi ne("");
myPersonCompare r.ComparisonMet hod =
PersonComparer. ComparisonType. LastName;
PersonList.Sort (myPersonCompar er);
foreach (Person p in PersonList) Console.Write(p .LastName
+ "|");
//works, sort by last name

Console.WriteLi ne("");
myPersonCompare r.ComparisonMet hod =
PersonComparer. ComparisonType. FirstName;
PersonList.Sort (myPersonCompar er);
foreach (Person p in PersonList) Console.Write(p .LastName
+ "|");
// works, sort by first name

// IComparer works for Array too

Person[] personArray = new Person[]{new Person("ray",
"lopez", 38), new Person("zoe", "smith", 28),new Person("nue",
"mather", 58)};
Array.Sort(pers onArray, myPersonCompare r);
foreach (Person p in personArray) Console.Write(p .LastName
+ "!");
Console.WriteLi ne("");
myPersonCompare r.ComparisonMet hod =
PersonComparer. ComparisonType. Age;
Array.Sort(pers onArray, myPersonCompare r);
foreach (Person p in personArray) Console.Write(p .LastName
+ "!!");
Console.WriteLi ne("\n");
}
}
}
///////////////////////////
/*
* smith|lopez|mat her| //<--List is sorted by Age
lopez|mather|sm ith| //<--Sorted by Last Name
mather|lopez|sm ith| //<--Sorted by First name
mather!lopez!sm ith! //<--now for an array, rather than
list, also works, sort by FirstName
smith!!lopez!!m ather!! <--sort array by age
Press any key to continue . . .
* */
////////////////////////////////////////////
using System;
using System.Collecti ons.Generic;
using System.Linq;
using System.Text;
using System.Diagnost ics;

namespace console1
{
class Person
{
public string LastName;
public int Age;
public string FirstName;

public Person(string fn, string ln, int age)
{
LastName = ln;
FirstName = fn;
Age = age;
}

public int CompareTo(Perso n p2, PersonComparer. ComparisonType
myCType)
{
switch (myCType)
{
case PersonComparer. ComparisonType. Age:
return Age.CompareTo(p 2.Age);
case PersonComparer. ComparisonType. LastName:
return LastName.Compar eTo(p2.LastName );
default:
return FirstName.Compa reTo(p2.FirstNa me);
}
}

}

class PersonComparer : IComparer<Perso n>
{
public enum ComparisonType
{ FirstName = 1, LastName = 2, Age = 3 }
private ComparisonType _comparisonType ;
public ComparisonType ComparisonMetho d
{
get { return _comparisonType ; }
set { _comparisonType = value; }
}

public int Compare(Person x, Person y)
{
Person p1;
Person p2;
if (x is Person) p1 = x as Person;
else
throw new ArgumentExcepti on("Object not type Person");
if (y is Person) p2 = y as Person;
else
throw new ArgumentExcepti on("Object not type Person");
return p1.CompareTo(p2 ,_comparisonTyp e);

}
} } ////////////////////

Sep 29 '08 #1
3 10555
There is no requirement that the query results be of strings. I think the
following example addresses what you are asking, but if not, please clarify.
It orders the people by age, then lastname, then firstname.

var ages = from p in PersonList orderby p.Age, p.LastName, p.FirstName
select p;
foreach (Person p in ages)
Console.Out.Wri teLine(p.LastNa me + " " + p.FirstName + " " + p.Age);
Console.In.Read Line();

"raylopez99 " <ra********@yah oo.comwrote in message
news:6c******** *************** ***********@y38 g2000hsy.google groups.com...
Question for the group: a suggestion in Albahari C#3 in a Nutshell
says you can, as an alternative to calling Sort, use LINQ's "OrderBy"
and "ThenBy" operators. Unlike Array.Sort or List.Sort, the LINQ
operators don't alter the original array or list, but instead emit the
sorted result in a fresh IEnumerable<Tse quence.

Any idea on how this can be done here? Remember, the
"strings" (LastName, FirstName) and "int" (Age) are stored inside a
class here, so it might be hard to do, since it seems to me LINQ
queries require something like string [] FirstName = {"Tom", "Dick",
"Harry"}; outside a class, rather than having the variables inside a
class as here.

If there's an easy way to use Linq, please post the complete code
otherwise just a hint or pseudocode.

Sep 30 '08 #2
On Sep 29, 7:26*pm, "Family Tree Mike"
<FamilyTreeM... @ThisOldHouse.c omwrote:
*I think the
following example addresses what you are asking, but if not, please clarify.
It orders the people by age, then lastname, then firstname.
Yes, it worked. That was deceptively easy; it makes me wonder why
even bother with IComparer, unless you want a permanent newly sorted
array or list.

Thanks, FTM, you're a real programmer.

RL
Sep 30 '08 #3
There is still good reason to impliment IComparer etc for a library class
intended for use in other systems. After all, the other system developer may
not know LINQ, or just may choose other mechanisms. But in a single
developer environment, you may be right.

"raylopez99 " wrote:
>
Yes, it worked. That was deceptively easy; it makes me wonder why
even bother with IComparer, unless you want a permanent newly sorted
array or list.
Sep 30 '08 #4

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

Similar topics

8
2493
by: Tom | last post by:
Has anyone ever seen a IComparer for floats the returns magnitude. i.e. instead of returning -1, it would return -5. To let you know HOW different the two numbers are. obviously for int it is a - b. But for float the results would have to be normalize some how to a 32bit range. I understand there would be percision errors. Thanks Tom
3
30177
by: Cybertof | last post by:
Hello, Could someone please explain me the difference between the 2 interfaces IComparable and IComparer ? In which cases use one or the other ? Are they dedicated to own classes or built-in collections ? Regards,
2
2920
by: Arulraja | last post by:
Hello, I have a custom collection object. each instance has FirstName and LastName. I want to sort this object collection by Last Name and First Name(ie if the last names are same I want to sub sort it by First Name). I know how to sort it by one value?(last Name) I am using the following code for this.It is working fine.
4
2370
by: CodeRazor | last post by:
Hi, I want to retrieve a sorted list of files, ordered by LastWriteTime. I know I can implement IComparer, but I don't know how or what this means. I know a sortedlist has objects and keys and that I could make the key for my sorted list the LastWriteTime of the file. Apart from this i'm at a real loose end. Any clues anyone?
6
3897
by: Robert Robbins | last post by:
Hello Programmers, I cannot figure out how to use the IComparer interface to sort an array based on the value of a double. I want to sort an array of dealers based on their distance from a zip code. The error this code gives me is "Specified IComparer threw an exception ." on the last line of code shown below. - Robert Robbins (Web Developer) Imports System.Collections
3
10279
by: RJN | last post by:
Hi I have a user defined data type which implements IComparable interface and has an implementation for the CompareTo method. Public Class MyDataType Implements IComparable --Private members --Public properties
10
2838
by: INeedADip | last post by:
I am trying to use a generic (reflection) IComparer class to sort a generic list but I get the error: Unable to cast object of type 'GenericComparer' to type 'System.Collections.Generic.Icomparer `1' My code looks like the following: List<AccountDB.Queue> oList = getAllQueuesFunction(); List.Sort(New GenericComparer("QueueName")); <-- Error
11
5018
by: solandre | last post by:
my motivation is as follows: i have to binarysearch several million times an long that is several million items big. this costs time, although i use Array.Binarysearch<long>. so i try to keep the Compare-method as lean as possible, as it is summoned several 10 million times. in case of an integer the fastest way would be this i think: public int Compare(int a, int b)
10
2535
by: Tony | last post by:
Hello! I'm reading in a book and this can't be correct it says. "Objects passed to Comparer.Compare() are checked to see if they support IComparable. If they do, then that implementation is used" Assume I have a collection of Item(s) in an ArrayList This class called Item support the IComparable interface which contains the CompareTo method
0
9516
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9351
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9286
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6774
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6062
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4587
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4840
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3294
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 we have to send another system
2
2768
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.