Created
April 16, 2020 20:13
-
-
Save enisn/8384999399f2b59f60d361d1b667c832 to your computer and use it in GitHub Desktop.
Challenge #1 - Solution 2 - Range{T}.cs
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
| public partial class Range<T> : IRange<T>, IEquatable<string>, IFormattable | |
| where T : struct, IComparable | |
| { | |
| public Range() | |
| { | |
| } | |
| public Range(string value) | |
| { | |
| var parsed = Parse<T>(value); | |
| this.Min = parsed.Min; | |
| this.Max = parsed.Max; | |
| } | |
| public Range(T? min, T? max) : this() | |
| { | |
| Min = min; | |
| Max = max; | |
| } | |
| public T? Min { get; set; } | |
| public T? Max { get; set; } | |
| public static implicit operator Range<T>(string val) | |
| { | |
| return Parse<T>(val); | |
| } | |
| public static Range<TParam> Parse<TParam>(string value) where TParam : struct, IComparable | |
| { | |
| var splitted = value.Split(' '); | |
| return new Range<TParam>( | |
| splitted[0] == null || splitted[0] == "-" ? default(TParam) : (TParam)Convert.ChangeType(splitted[0], typeof(TParam)), | |
| splitted[1] == null || splitted[1] == "-" ? default(TParam) : (TParam)Convert.ChangeType(splitted[1], typeof(TParam)) | |
| ); | |
| } | |
| public static explicit operator string(Range<T> val) | |
| { | |
| return val.ToString(); | |
| } | |
| public override string ToString() | |
| { | |
| return $"{this.Min?.ToString() ?? "-"} {this.Max?.ToString() ?? "-"}"; | |
| } | |
| public Expression BuildExpression(Expression body, PropertyInfo property, object value) | |
| { | |
| return GetRangeComparison(); | |
| BinaryExpression GetRangeComparison() | |
| { | |
| BinaryExpression minExp = default, maxExp = default; | |
| if (Min != null) | |
| { | |
| minExp = Expression.GreaterThanOrEqual( | |
| Expression.Property(body, property.Name), | |
| Expression.Constant(Min)); | |
| if (Max == null) | |
| return minExp; | |
| } | |
| if (Max != null) | |
| { | |
| maxExp = Expression.LessThanOrEqual( | |
| Expression.Property(body, property.Name), | |
| Expression.Constant(Max)); | |
| if (Min == null) | |
| return maxExp; | |
| } | |
| return Expression.And(minExp, maxExp); | |
| } | |
| } | |
| public bool Equals(string other) | |
| { | |
| return this.ToString() == other; | |
| } | |
| public string ToString(string format, IFormatProvider formatProvider) | |
| { | |
| return this.ToString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment