14

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!

asked Jul 22, 2011 at 13:16
1

6 Answers 6

22

You can do it using Comparision delegate, using Sort(Comparision<T> comparision) overload.

list.Sort((a, b) => a.StringProperty.CompareTo(b.StringProperty));
answered Jul 22, 2011 at 13:20
0
17

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);
answered Jul 22, 2011 at 13:18
0
4

Assuming that your collection implements the IEnumerable interface, you can simply call the OrderBy method on your collection:

myCollection.OrderBy(c => c.Property);
answered Jul 22, 2011 at 13:19
2
var list = new List<SomeClass>();
// add some instances of SomeClass to list
list.Sort((x, y) => x.SomeProperty.CompareTo(y.SomeProperty));
answered Jul 22, 2011 at 13:21
2

Convert the code to C# ,

If you have an list object ABC with a string property S for each objects in the list ,

Dim Mylist As New List(Of ABC)

 Dim a = From i In Mylist _
 Order By i.S Ascending

you will have teh result in a , put on a iterator .

answered Jul 22, 2011 at 13:23
0

Be sure to include System.Collections.Generic and System.Linq.

 List<myItemType> lst = new List<myItemType>();
 return lst.OrderBy(i => i.StringPropertyName);
answered Jul 22, 2011 at 13:21
1
  • Hi Jason - it returns an enumerable instance where the enumeration will be ordered. I suppose you could do lst = new List<myItemType>(lst.OrderBy(...)); Commented Jul 22, 2011 at 13:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.