Last active
August 29, 2015 14:24
-
-
Save wonderful-panda/06cc8fdad28abf09597c to your computer and use it in GitHub Desktop.
複数のキーで比較を行うComparer
This file contains hidden or 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
| // OrderBy(x => x.Id).ThenBy(x => x.Name) みたいな比較をするComparer | |
| // var comparer = KeyComparer<Foo>.CreateBy(x => x.Id).ThenBy(x => x.Name); みたいに使う | |
| public class KeyComparer<T> : IComparer<T> | |
| { | |
| readonly List<Comparison<T>> comparisons_; | |
| private KeyComparer(params Comparison<T> []comparisons) | |
| { | |
| comparisons_ = comparisons.ToList(); | |
| } | |
| public int Compare(T x, T y) | |
| { | |
| var ret = 0; | |
| foreach (var c in comparisons_) | |
| { | |
| ret = c(x, y); | |
| if (ret != 0) | |
| break; | |
| } | |
| return ret; | |
| } | |
| public static KeyComparer<T> CreateBy<TKey>(Func<T, TKey> selector) | |
| where TKey: IComparable | |
| { | |
| return new KeyComparer<T>((T x, T y) => Comparer<TKey>.Default.Compare(selector(x), selector(y))); | |
| } | |
| public KeyComparer<T> ThenBy<TKey>(Func<T, TKey> selector) | |
| where TKey: IComparable | |
| { | |
| // イミュータブルにして別のインスタンスを返すようにした方がいいかも | |
| comparisons_.Add((T x, T y) => Comparer<TKey>.Default.Compare(selector(x), selector(y))); | |
| return this; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment