1

I'm converting my application from .Net 4.0 to .Net 4.5 Framework and there is a change in the List<> definition. My old code looked like this (.Net 4.0):

List<Customer> list = new List<Customer>();
list.Add(new Customer("Smith", "John", "Sydney", 45));    
list.Add(new Customer("Mitchell", "Brad", "New York", 52));
list.Add(new Customer("Baker", "William", "Cape Town", 21)); 
list.OrderBy(x => x.Name);

Using .Net 4.5 (C#5) the List<T>.OrderBy() method is gone and only List<T>.Sort() is available, but it looks like there is no possibility to use a Lambda expression with this method.

Is there any option other than defining a IComparer for every <T>? If there is really no option for a Lambda expression, I could life with a generic IComparer, but how to choose the property to be compared?

Solved/Edit:

using Linq;
[...]
List<Customer> list = new List<Customer>();
list.Add(new Customer("Smith", "John", "Sydney", 45));    
list.Add(new Customer("Mitchell", "Brad", "New York", 52));
list.Add(new Customer("Baker", "William", "Cape Town", 21)); 
list.OrderBy(x => x.Name); //list stays unordered
list = list.OrderBy(x => x.Name).ToList();  // list content is now ordered
svick
  • 236,525
  • 50
  • 385
  • 514
MikeR
  • 3,045
  • 25
  • 32

1 Answers1

4

List<T>.OrderBy() is not gone, it's still an extension method

You have to use

using System.Linq;

to make it work

In your code, you should use "list.OrderBy(x => x.Name);"

svick
  • 236,525
  • 50
  • 385
  • 514
Bruno
  • 623
  • 2
  • 9
  • 24
  • Thanks, but why is it an extension and not part of List? How should I know if there is somewhere an extension I could need? Maybe my "mistake" was to clean the using before converting :( – MikeR Jan 25 '13 at 14:19
  • OrderBy is an extension method of IEnumerable and List inherit of IEnumerable so you can use it in List. The intellisence doesn't tell you much if there is an extension method that you could use, so I guess the only way would be to look at the msdn documentation – Bruno Jan 25 '13 at 14:24
  • Yes, but it's hard to search, when you don't know what you are looking for. Also there seems to be a change in handling the OrderBy, as you can see in my edit above. – MikeR Jan 25 '13 at 14:35
  • I guess they made OrderBy lazy http://stackoverflow.com/questions/2530755/difference-between-deferred-execution-and-lazy-evaluation-in-c-sharp – Bruno Jan 25 '13 at 14:43