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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With