Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting object list by string property C# [duplicate]

Tags:

c#

.net

Possible Duplicates:
Sorting a list using Lambda/Linq to objects
C# List<> OrderBy Alphabetical Order

How do I go about sorting a list of objects in alphabetical order by a string property.

I have tried implementing IComparable on the property but I only figured out how to sort on the first character (using char).

EDIT: Here is some sample code.

class MyObject {
    public string MyProperty {get;set;}
}

List<MyObject> sampleList = new List<MyObject>();    

MyObject sample = new MyObject();
sample.MyProperty = "Aardvark";

MyObject sample2 = new MyObject();
sample2.MyProperty = "Zebra";

sampleList.Add(sample);
sampleList.Add(sample2);

sampleList.Sort(); // or something similar

foreach (var item in sampleList) {
    Console.WriteLine(item.MyProperty);
}

Should output Aardvark and Zebra (in alphabetical order).

Thanks!

like image 300
Jeffrey Kevin Pry Avatar asked Jul 22 '11 13:07

Jeffrey Kevin Pry


1 Answers

You can get a sorted IEnumerable<MyObject> like so:

var sortedQuery = sampleList.OrderBy(x => x.MyProperty);

You can then either convert the query to a list like so:

var sortedList = sortedQuery.ToList();

Or, you can just iterate through the items:

foreach (var obj in sortedQuery)
    Console.WriteLine(obj.MyProperty);
like image 173
dlev Avatar answered Sep 22 '22 13:09

dlev