Solved

How to sort an IList of custom objects?

Posted on 2008-10-28
13
2,727 Views
Last Modified: 2012-05-05
In my C# project, I have a typed IList of custom objects:  IList<MyObject>.
I need to sort the IList based on a specific property of
my object.  How can I do that?
0
Comment
Question by:JeffDrummond
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 3
  • +1
13 Comments
 
LVL 21

Expert Comment

by:silemone
ID: 22821997
you can make a comparator class

http://geekswithblogs.net/paulwhitblog/archive/2006/05/08/77581.aspx has an example
0
 
LVL 21

Accepted Solution

by:
silemone earned 250 total points
ID: 22822063
By the way, comparator is what it would be called in java....should call it a comparer in C#...
Also the code will work perfectly, but it will use natural comparer, i.e. alphabetical, numerical, etc...
If you want to compare by your own value, put the comparison in there yourself...

i.e. if yo want to compare by name field...

do something like this


return object1.Name.CompareTo(object2.Name);
if address

return object1.Address.CompareTo(object2.Address

even have multiple comparing


if (object1.Name.Equals(Object2.Name))
    return object1.Address.CompareTo(object2.Address);
0
 
LVL 22

Assisted Solution

by:p_davis
p_davis earned 250 total points
ID: 22822517
yourList.Sort(delegate(YourClass yc1 , YourClass yc2){return yc1.YourProperty.CompareTo(yc2.YourProperty);});
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 12

Expert Comment

by:jandromeda
ID: 22827164
Try the following code. Student is the comparable custom object. Hope this helps you.
/*
 * Created by SharpDevelop.
 * User: Sajeewaa
 * Date: 10/28/2008
 * Time: 6:35 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections;
using System.Collections.Generic;
 
namespace ExpertsExchange
{
	/// <summary>
	/// Description of Student.
	/// </summary>
	public class Student : IComparer<Student>
	{
		private int _marks;
		private string _name;
		
		public int Marks {
			get { return _marks; }
			set { _marks = value; }
		}
		
		public string Name {
			get { return _name; }
			set { _name = value; }
		}
		
		public Student()
		{}
		
		public Student(int marks, string name)
		{
			this._marks = marks;
			this._name = name;
		}
		
		/// <summary>
		/// Compare Student object based on the marks.
		/// </summary>
		/// <param name="x"></param>
		/// <param name="y"></param>
		/// <returns></returns>
		public int Compare(Student x, Student y)
		{
			return x.Marks.CompareTo(y.Marks);
		}
	}
}
 
 
// Test method
public static void SortStudents()
		{
			List<Student> students = new List<Student>();
			
			students.Add(new Student(75, "Jason"));
			students.Add(new Student(58, "Neomi"));
			students.Add(new Student(45, "Jack"));
			students.Add(new Student(80, "Horianna"));
			students.Add(new Student(35, "Tom"));
			
			Student comp = new Student();
			
			students.Sort(comp);
			
			foreach (Student item in students)
			{
				Console.WriteLine(item.Name);
			}
		}

Open in new window

0
 

Author Comment

by:JeffDrummond
ID: 22844176
The following code sorts on the first property, but I am not quite sure from the comments above how to sort on a  second or third property.  Can you add to the code below and show me how to additionally sort based on a property called Type?  

            if (myList.Count > 1)
            {
                ((List<DetailView>)myList).Sort(delegate(DetailView td1, DetailView td2) { return td1.Description.CompareTo(td2.Description); });
            }

Thanks!
0
 

Author Comment

by:JeffDrummond
ID: 22844192
BTW, myList in the example is an IList, that's why I am typing it to a List, in order to get to the Sort method.
0
 
LVL 22

Expert Comment

by:p_davis
ID: 22844212
do you mean that you want to sort on one property and then on another consecutively? can you give a small example of data and the results that you would expect to see?
0
 

Author Comment

by:JeffDrummond
ID: 22844250
Yes, it be like an ORDER BY in SQL, such as:

ORDER BY Description, Type;
0
 
LVL 22

Expert Comment

by:p_davis
ID: 22844834
you originally asked how to sort on A property -- that's all this will do --
you will probably have to go with a comparer derived class to get the "order by" functionality, not quite sure how you would do that off the top of my head. i will try to work on it -- maybe in the meantime someone else will pop up with the answer.
0
 

Author Comment

by:JeffDrummond
ID: 22850240
This code is working correctly for me.  It types myList (an IList) to a List
object to gain access to the List.Sort method.  The first level of comparison
is on the Description property.  If the values are equal, it goes to the second
level of comparison on the Type property.

            if (myList.Count > 1)
            {
                ((List<DetailView>)myList).Sort(delegate(DetailView d1, DetailView d2)
                {
                    if (d1.Description.Equals(d2.Description))
                    {
                        return d1.Type.CompareTo(d2.Type);
                    }
                    else
                    {
                        return d1.Description.CompareTo(d2.Description);
                    }
                });
            }

Thanks for your help.
0
 

Author Closing Comment

by:JeffDrummond
ID: 31510738
Together, both answers provided the information I needed.
0
 
LVL 22

Expert Comment

by:p_davis
ID: 22850266
cool
0
 
LVL 21

Expert Comment

by:silemone
ID: 22850340
Glad i could a part of the solution.  

Cheers.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Suggested Courses

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question