Created
November 22, 2022 18:36
-
-
Save joeskeen/d9a175bb0bd459068df0c974977df9f2 to your computer and use it in GitHub Desktop.
Ordering objects with LINQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var apples = new[] { new Apple("Red"), new Apple("Blue"), new Apple("Green") }; | |
var oranges = new[] { new Orange(Size.Large), new Orange(Size.Small), new Orange(Size.Medium) }; | |
// works | |
Console.WriteLine(string.Join(',', apples.OrderBy(x => x))); | |
// throws InvalidOperationException | |
Console.WriteLine(string.Join(',', oranges.OrderBy(x => x))); | |
class Apple : IComparable<Apple> | |
{ | |
public readonly string Color; | |
public Apple(string color) | |
{ | |
Color = color; | |
} | |
public int CompareTo(Apple? other) | |
{ | |
return this.Color.CompareTo(other?.Color); | |
} | |
public override string ToString() | |
{ | |
return $"{Color} apple"; | |
} | |
} | |
class Orange | |
{ | |
public readonly Size Size; | |
public Orange(Size size) | |
{ | |
Size = size; | |
} | |
public override string ToString() | |
{ | |
return $"{Size} orange"; | |
} | |
} | |
enum Size { Small, Medium, Large } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment