-1

I add Custom type: Task in to the list.

e.g.

Task t1 = new Task();

result.Add(t1);

Now i want to order 'result' by the EndDate property of Task class.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Implement IComparable interface inside of the class and then you'll be able to sort a list containing elements of that type. http://stackoverflow.com/questions/4188013/c-sharp-interfaces-how-to-implement-icomparable – Alex Dec 15 '15 at 14:55
  • 1
    Possible duplicate of [How to Sort a List by a property in the object](http://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – Sayse Dec 15 '15 at 14:57
  • What is `result`? What have you tried to order them? – krillgar Dec 15 '15 at 14:57
  • Duplicate was very first google result for "c# order by property" – Sayse Dec 15 '15 at 14:57
  • If you're sure you have nothing but `Task` instances in your list, use [`Enumerable.Cast()`](https://msdn.microsoft.com/library/bb341406%28v=vs.110%29.aspx), i.e. `var ordered = result.Cast().OrderBy(t => t.EndDate).ToList();` But better to use `List` as everyone says. – dbc Dec 15 '15 at 18:48

3 Answers3

2

You should use List<Task> instead of List<object> then you can use OrderBy Like this:

var sorted = result.OrderBy(c => c.EndDate);

Or:

var sorted = result.OrderByDescending(c => c.EndDate);

Or:

var sorted = result.OrderByDescending(c => c.EndDate).ToList();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • But i have an existing code where List has been implemented and used in many other references. – Mrudang Dalal Dec 16 '15 at 12:04
  • @MrudangDalal ...Well if you want to keep the `result` as a `List` you can define another `List` like this: `List result = new List(); List result2 = result.Cast().ToList();` and then: `var sorted = result2.OrderByDescending(c => c.EndDate);` If you didn't understand tell me so that I update my answer and explain it more. – Salah Akbari Dec 16 '15 at 12:14
  • Excellent. It worked. Actually after your suggestion i made it more easier. List result = new List(); result = result.OrderBy(x => x.EndDate).ToList(); return result.ToList(); – Mrudang Dalal Dec 17 '15 at 05:07
1

What you need is a List<Task> to be the type of result. Right now you have List<object> and you can't access EndDate property without casting.

List<Task> result = new List<Task>();
Task t1 = new Task();
result.Add(t1);

and then for sorting you can use OrderBy or OrderByDescending

var sortedQuery = result.OrderBy(r=> r.EndDate);

If you need a List<Task> then append ToList(); to the query.

Also, you may change your class name to something different, as there is a Task class available in .Net framework as well.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

You can use LINQ by a typed List<>.

For example:

List<Task> result = new List<Task>();

result.Add(Task1);
result.Add(Task2);

return result.OrderBy(x => x.EndDate).ToList();