Skip to content

Instantly share code, notes, and snippets.

@joeskeen
Created November 22, 2022 18:36
Show Gist options
  • Save joeskeen/d9a175bb0bd459068df0c974977df9f2 to your computer and use it in GitHub Desktop.
Save joeskeen/d9a175bb0bd459068df0c974977df9f2 to your computer and use it in GitHub Desktop.
Ordering objects with LINQ
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