13

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,182
  • 3
  • 32
  • 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

21

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

list.Sort((a, b) =>  a.StringProperty.CompareTo(b.StringProperty));
George Polevoy
  • 6,775
  • 3
  • 30
  • 58
16

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
  • 46,018
  • 5
  • 113
  • 128
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
  • 18,293
  • 2
  • 44
  • 61
2
var list = new List<SomeClass>();
// add some instances of SomeClass to list
list.Sort((x, y) => x.SomeProperty.CompareTo(y.SomeProperty));
jason
  • 220,745
  • 31
  • 400
  • 507
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
  • 159
  • 1
  • 2
  • 11
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,688
  • 13
  • 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