0

I am trying to sort a generic list, and am getting a InvalidOperationException error

Does anyone has suggestions on how to rectify it?

List<XYZ<String, String>> list is being passed on as a parameter through a function.

func( List<XYZ<String, String>> PassedList) {

   PassedList.Sort();
}

Any suggestion would be really helpful.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
SonalKhodiyar
  • 695
  • 8
  • 16
  • What's the detail message of the InvalidOperationException? – dtb Feb 14 '13 at 17:59
  • XYZ will need to inherit from http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx if it doesn't allready (if it does, please provide the code for the CompareTo func) and provide a suitable implementation - List.Sort uses the CompareTo function. http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx – VisualMelon Feb 14 '13 at 18:00

3 Answers3

2

Your XYZ should be IComparable

dead_ant
  • 124
  • 4
1

Your XYZ must implement IComparable or (better yet) IComparable<XYZ<T, U>>.

If that's not possible, you must either create a class that implements IComparer or (again, better yet) IComparer<XYZ<String, String>> and use the overload of Sort() that takes an instance of such an object, or else use the form that takes a delegate or lamda expression that matches Comparison<XYZ<String, String>> (taking two XZY<String, String> arguments, and returning int).

If the Sort() method can't work out which XYZ comes before which, then it can't sort them.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
  • Thank you Jon. I was trying to keep the code as simple as possible and hence tried linq and succeeded – SonalKhodiyar Feb 14 '13 at 19:06
  • The linq version deals with it in a slightly different way. If it's a large list (or could be) it may be worth looking at the details more, as there are cases where a lists `Sort()` method is considerably more performant than `OrderBy()`, though also some where the opposite holds. If it's always a small list, then I wouldn't worry about that side of it. – Jon Hanna Feb 15 '13 at 16:51
  • I'll keep that in mind for future use. thank you for sharing. – SonalKhodiyar Feb 15 '13 at 16:54
0

I resolved the issue using linq statement.

rather than using PassedList.Sort(), I used the following statement:

PassedList = PassedList.OrderBy( x => x.Column1).ToList();
SonalKhodiyar
  • 695
  • 8
  • 16