views:

61

answers:

3

Hi

I have a List of classes in my collection like

List<MyClass> test = new List<MyClass>();

In my classes I have just some properties

public string id {get; set;}
public DateTime date {get; set;}

Now I make these classes by getting some queries from 2 different database tables. I then take those 2 results from the database tables and using a foreach loop I make a new MyClass object and stick it in my "test" collection.

Now once all these classes are put in the the list collection. I want to sort through them and order the classes by the "date" property.

How could I do this? I can't order then right when I get them from the database since I am getting them from 2 different database tables and ordering them separately would only make it ordered in for each section but table one might have 12/12/2009 and so might table two. So they need to be ordered together.

So can I some how use linq or something to order them?

Thanks

+2  A: 

Once you have your classes in your list, and the list is complete:

List<MyClass> testList = new List<MyClass>();
// populate the list...

var orderedList = testList.OrderBy( x => x.date ).ToList();
LBushkin
Ah I tried that but did not put .ToList() behind it. I seen some people use the compare function does that bring any advantages or anything?
chobo2
+6  A: 

How about:

list.Sort((x,y) => DateTime.Compare(x.date, y.date));

which sorts the existing list, or:

var sorted = list.OrderBy(x=>x.date).ToList();

which creates a second list.

Marc Gravell
Ya as I mentioned below I tried to do the second way before I posted but did not use .ToList() So orderBy always creates a new list while sort does not?
chobo2
Yes. List.Sort sorts the list in place, so the original list is altered. LINQ (the second method) creates a new enumerable. By adding "ToList", you turn it into a List<MyClass> instead of IEnumerable<MyClass>. If you're just going to use the results in a foreach loop, you can leave the "ToList()" method off.
Reed Copsey
(what he said...)
Marc Gravell
+2  A: 

If you want to sort them in place, you can use List<T>.Sort:

test.Sort( (l,r) => l.date.CompareTo(r.date) );

If you want to sort them into a new result set, LINQ is very nice:

var sortedResults = from mc in test
                    order by mc.date
                    select mc;
Reed Copsey