C# Sorting | Sololearn: Learn to code for FREE!


C# Sorting

I try to sort a list of objects using icompare. I Want to be able to sort the objects with different criterias. How do I pass the criteria to the sorting class? Here i am using the constructor. Is there a better Way? https://code.sololearn.com/c6bzHS2Vyd9z/?ref=app

2/16/2022 7:29:26 AM

Joakim Eriksson

3 Answers

New Answer


The best way is to use OrderBy method of Linq, if you only need to compare by certain fields individually. No need to use complicated design patterns, or to write separate comparator classes. I also suggest you to review and follow C# coding style recommendations: - class names and public field and method names should generally start with capital letter - variable names start with lowercase If you follow the same pattern as every other developer, your code will be easier to read (and comment) for everyone. Another suggestion, regarding your code: when you need to switch between a finite and limited set of options, defining an enum is usually a better idea than using strings. Anyway here is my own suggested implementation: https://code.sololearn.com/cmE5g94XV1DD/?ref=app