[RESOLVED] Double sorting of a list
Hi all,
I have been learning how to sort a list using lambda functions
Code:
excessPop.Sort(Function(f1, f2) f1.ID.CompareTo(f2.ID))
I am however struggling to sort a list using 2 parameters within a lambda function. The properties within my list that i need to sort by are Category and then by Cost.
Any pointers for how to do this?
Re: Double sorting of a list
This should work:
vb.net Code:
excessPop.Sort(Function(f1, f2) If(f1.Category.CompareTo(f2.Category) = 0, _
f1.Cost.CompareTo(f2.Cost), _
f1.Category.CompareTo(f2.Category))
It's a bit clumsy because it will compare the Category values twice if they are not the same but, until .NET 4.0 and multiline lambdas, that's what you're stuck with.
Re: Double sorting of a list
thanks chcilhinney your a star ;) one further question tho, what if i needed to sort by descending cost, how would i change the lambda expression to achieve this?
Re: Double sorting of a list
worked it out :) thanks again for the help.
wont let me rate you lol
Re: Double sorting of a list
For completion this is how to change to descending for Cost
vb.net Code:
excessPop.Sort(Function(f1, f2) If(f1.Category.CompareTo(f2.Category) = 0, _
f2.Cost.CompareTo(f1.Cost), _
f1.Category.CompareTo(f2.Category))
Re: Double sorting of a list
Quote:
Originally Posted by
Megalith
thanks chcilhinney your a star ;) one further question tho, what if i needed to sort by descending cost, how would i change the lambda expression to achieve this?
Think about it. What does the CompareTo method actually do? It returns an Integer that indicates the relative order of the two values. Less than zero mean the first item comes before the second, greater than zero means the second item comes before the first and zero means that the two items are equivalent. With that in mind, what do you think you need to change here:
Code:
f1.Cost.CompareTo(f2.Cost)
to make it sort in the opposite direction?
That's how you need to approach problems like this. You don't just look at the code as a single unit. You break it down and ask yourself what each element of the code is actually doing. You can then look at how that fits into the whole and what adjustments you can make to change the way the whole works.
EDIT: I guess you did think about it after all. :thumb: You could have done that before I started typing out that long-winded response though. ;)