Sorting a ArrayList on multiple fields
-
I am looking for a way to sort an ArrayList on Multiple fields similar to the following. eg. select * from table1 order by col1 desc, col2 asc, col3 desc. I have implemented the IComparer for the different fields. I am not sure how to go forward from here. I am trying to achieve best performance.
-
I am looking for a way to sort an ArrayList on Multiple fields similar to the following. eg. select * from table1 order by col1 desc, col2 asc, col3 desc. I have implemented the IComparer for the different fields. I am not sure how to go forward from here. I am trying to achieve best performance.
alam_pune wrote:
I am looking for a way to sort an ArrayList on Multiple fields similar to the following. eg. select * from table1 order by col1 desc, col2 asc, col3 desc. I have implemented the IComparer for the different fields. I am not sure how to go forward from here. I am trying to achieve best performance.
Hmm, I think what you need to do is implement IComparer for each select statement. You'll need to implement an IComparer that sorts not just on one field but on all of them, or at least the ones in your select statement. So to use your example, your IComparer would first compare the values in the first column between two items. If they aren't equal, you can stop the comparison and return the result. If they are equal, you move on to the next column and make a comparison there. Again, if they aren't equal, you can stop the comparisons and return the result. Else, you move on to the third column, and so on. The value of the result of each comparison will depend on the ordering you want, descending or ascending. I think this is what you're looking for. Hope this helps.
-
alam_pune wrote:
I am looking for a way to sort an ArrayList on Multiple fields similar to the following. eg. select * from table1 order by col1 desc, col2 asc, col3 desc. I have implemented the IComparer for the different fields. I am not sure how to go forward from here. I am trying to achieve best performance.
Hmm, I think what you need to do is implement IComparer for each select statement. You'll need to implement an IComparer that sorts not just on one field but on all of them, or at least the ones in your select statement. So to use your example, your IComparer would first compare the values in the first column between two items. If they aren't equal, you can stop the comparison and return the result. If they are equal, you move on to the next column and make a comparison there. Again, if they aren't equal, you can stop the comparisons and return the result. Else, you move on to the third column, and so on. The value of the result of each comparison will depend on the ordering you want, descending or ascending. I think this is what you're looking for. Hope this helps.