Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sort using comparer #224

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions src/Silverback.Core/Util/EnumerableSortExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,21 @@ internal static class EnumerableSortExtensions
{
public static IEnumerable<T> SortBySortIndex<T>(this IEnumerable<T> items)
{
var list = items.ToList();

var sortables = list.OfType<ISorted>().OrderBy(sorted => sorted.SortIndex).ToList();
var notSortables = list.Where(item => item is not ISorted).ToList();
return items.OrderBy(item => item, new SortedComparer<T>());
}

return sortables.Where(sorted => sorted.SortIndex <= 0).Cast<T>()
.Union(notSortables)
.Union(sortables.Where(b => b.SortIndex > 0).Cast<T>());
private sealed class SortedComparer<T> : IComparer<T>
{
public int Compare(T x, T y)
{
return (x, y) switch
{
(ISorted xSorted, ISorted ySorted) => xSorted.SortIndex.CompareTo(ySorted.SortIndex),
(ISorted xSorted, _) => xSorted.SortIndex > 0 ? 1 : -1,
(_, ISorted ySorted) => ySorted.SortIndex > 0 ? -1 : 1,
_ => 0
};
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ public void SortBySortIndex_SomeItems_SortedAsExpected()
new SortedItem(50),
new SortedItem(-100),
new Item("unsorted3"),
new Item("unsorted2")
new Item("unsorted2"),
new SortedItem(0)
};

var sorted = items.SortBySortIndex();
Expand All @@ -30,6 +31,7 @@ public void SortBySortIndex_SomeItems_SortedAsExpected()
{
new SortedItem(-100),
new SortedItem(-50),
new SortedItem(0),
new Item("unsorted3"),
new Item("unsorted2"),
new SortedItem(50),
Expand Down