Click here to Skip to main content
15,389,584 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 27 Jan 2013

Tagged as

Stats

21.5K views
8 bookmarked

Sorting C# collections that have no collating sequence

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
28 Jan 2013CPOL1 min read
This is an alternative for "Sorting using C# Lists"

Introduction

This Tip/Trick is an alternative to the original tip Sorting using C# Lists[^].

You often face the issue that a given class has not one Collating Sequence[^] but many various ways to order the class objects. This alternative tip shows how to choose the ordering without depending on the class implementing IComparable[^].

Sorting alternatives to "hard coded" IComparable dependency

A class that has no natural Collating Sequence[^] should not implement IComparable<T>. Instead, one should use a per case defined ordering. Some concise solutions are shown below. They do not need any definition of any additional IComparer class nor do they require the element class to implement IComparable.

By LINQ means

Sorting by LINQ is as follows:
C#
var querySortedByProperty = from element in collection
                            orderby element.property
                            select element;
foreach(var item in querySortedByProperty) { ... }

By Enumerable extension methods

Sorting equivalent to LINQ by Enumerable[^] extension method calls:
C#
var querySortedByProperty = collection.OrderBy(e=>e.property);
foreach(var item in querySortedByProperty) { ... }

By Sorting overload

Sorting a colleciton is also possible by a Sort overload that takes a delegate for ordering the elements of the collection:
C#
collection.Sort((a,b)=>a.property.CompareTo(b.property));
foreach(var item in colleciton) { ... }

Using the code

Assuming the following class analogous to the one from the original tip without implementing IComparable<T>.

C#
public class Student
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }
}
Linq:
C#
var querySortByName = from s in students orderby s.Name select s;
C#
var querySortByAge = from s in students orderby s.Age select s;
Extension methods:
C#
var querySortByName = students.Orderby(s=>s.Name);
C#
var querySortByAge = students.Orderby(s=>s.Age);
Sort collection:
C#
students.Sort((a,b)=>a.Name.CompareTo(b.Name));
C#
students.Sort((a,b)=>a.Age.CompareTo(b.Age));

Points of Interest

Checkout 101 LINQ samples[^]. That gives many first steps on LINQ operations.

History

V1.02013-01-26Initial version.
V1.12013-01-28Fixed some typos.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andreas Gieriet
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

Comments and Discussions

 
Questionhelpful Pin
Member 871442118-May-16 10:56
MemberMember 871442118-May-16 10:56 
GeneralMy vote of 5 Pin
adriancs28-Jan-13 14:49
professionaladriancs28-Jan-13 14:49 
GeneralRe: My vote of 5 Pin
Andreas Gieriet28-Jan-13 17:19
professionalAndreas Gieriet28-Jan-13 17:19 
GeneralMy vote of 5 Pin
Thomas Daniels28-Jan-13 6:13
mentorThomas Daniels28-Jan-13 6:13 
GeneralRe: My vote of 5 Pin
Andreas Gieriet28-Jan-13 7:09
professionalAndreas Gieriet28-Jan-13 7:09 
GeneralMy vote of 5 Pin
SRIRAM 227-Jan-13 22:23
MemberSRIRAM 227-Jan-13 22:23 
GeneralRe: My vote of 5 Pin
Andreas Gieriet27-Jan-13 22:24
professionalAndreas Gieriet27-Jan-13 22:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.