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!

Community
  • 1
  • 1
Jeffrey Kevin Pry
  • 3,266
  • 3
  • 35
  • 67
  • Maybe this helps http://stackoverflow.com/questions/722868/sorting-a-list-using-lambda-linq-to-objects – evilone Jul 22 '11 at 13:19

6 Answers6

22

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

list.Sort((a, b) =>  a.StringProperty.CompareTo(b.StringProperty));
George Polevoy
  • 7,450
  • 3
  • 36
  • 61
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);
dlev
  • 48,024
  • 5
  • 125
  • 132
4

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

myCollection.OrderBy(c => c.Property);
Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
2
var list = new List<SomeClass>();
// add some instances of SomeClass to list
list.Sort((x, y) => x.SomeProperty.CompareTo(y.SomeProperty));
jason
  • 236,483
  • 35
  • 423
  • 525
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 .

NO Name
  • 169
  • 1
  • 2
  • 12
0

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

    List<myItemType> lst = new List<myItemType>();
    return lst.OrderBy(i => i.StringPropertyName);
Brian
  • 2,772
  • 15
  • 12
  • Hi Jason - it returns an enumerable instance where the enumeration will be ordered. I suppose you could do lst = new List(lst.OrderBy(...)); – Brian Jul 22 '11 at 13:27