CodeDesignPatterns / Comparator

0 stars 0 forks source link

Comparer - C# #4

Open Unknown3134 opened 2 years ago

Unknown3134 commented 2 years ago

Challenge accepted by @PaulAtkins88 to do custom Comparer (say for Chicken to always be first element) class and find a neat way to pass it as an argument (Like Java streams). Not sure if LINQ supports this

Unknown3134 commented 2 years ago

Further investigation shows whilst you can use LINQ to sort by a property (and therefore not needing a comparer) so ignore LINQ for now.

See note below, but LINQ does NOT sort in place

Unknown3134 commented 2 years ago

C# List Sort method

The Sort method sorts the elements or a portion of the elements in the list.

The method has four overloads:

Sort(Comparison<T>) - Sorts the elements in the entire List<T> using the specified Comparison<T>.
Sort(Int32, Int32, IComparer<T>) - Sorts the elements in a range of elements in List<T> using the specified comparer.
Sort() - Sorts the elements in the entire List<T> using the default comparer.
Sort(IComparer<T>) - Sorts the elements in the entire List<T> using the specified comparer.

Note: The Sort method sorts the list in-place, while the LINQ's OrderBy method returns a sorted enumeration of list elements.

The comparison method

The sorting algorithms are already built into the standard library of the language. If the data is not sorted naturally, we need to provide a comparison method (either a class method or a lambda expression) which tells the underlying sorting algorithm how to sort the data. What attributes to sort and in what way.

public int CompareTo(Card other) { var index = Rank.CompareTo(other.Rank); if (index == 0) index = Suit.CompareTo(other.Suit); return index; }

For instance, this comparison class method tells to sort the objects by the Rank and if the rank is the same, then by Suit. We always compare two elements; in our case, two card objects. The comparison method returns 0 in case the elements are equal, -1 when the first element is less than the second, and 1 when the first element is greater than the second.

Oftentimes, our comparison function calls other comparison functions; in our case, the Rank and the Suit are enumerations and we compare them by the built-in CompareTo method.

Source: ( https://zetcode.com/csharp/sortlist/)