Mercurial > silverbladetech
comparison Chronosv2/source/Extensions/ComparableExtensions.cs @ 10:443821e55f06
Initial cleaned up add from Codeplex files
author | stevenh7776 stevenhollidge@hotmail.com |
---|---|
date | Tue, 21 Feb 2012 17:25:44 +0700 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
9:904a9faadf8b | 10:443821e55f06 |
---|---|
1 using System; | |
2 using System.Collections.Generic; | |
3 | |
4 namespace Chronos.Extensions | |
5 { | |
6 /// <summary> | |
7 /// Extension methods for all comparable objects eg. string, DateTime, numeric values ... | |
8 /// </summary> | |
9 public static class ComparableExtensions | |
10 { | |
11 | |
12 /// <summary> | |
13 /// Determines whether the specified value is between the the defined minimum and maximum range (including those values). | |
14 /// </summary> | |
15 /// <typeparam name="T"></typeparam> | |
16 /// <param name="value">The value.</param> | |
17 /// <param name="minValue">The minimum value.</param> | |
18 /// <param name="maxValue">The maximum value.</param> | |
19 /// <returns> | |
20 /// <c>true</c> if the specified value is between min and max; otherwise, <c>false</c>. | |
21 /// </returns> | |
22 /// <example> | |
23 /// var value = 5; | |
24 /// if(value.IsBetween(1, 10)) { | |
25 /// // ... | |
26 /// } | |
27 /// </example> | |
28 public static bool IsBetween<T>(this T value, T minValue, T maxValue) where T : IComparable<T> | |
29 { | |
30 return IsBetween(value, minValue, maxValue, null); | |
31 } | |
32 | |
33 /// <summary> | |
34 /// Determines whether the specified value is between the the defined minimum and maximum range (including those values). | |
35 /// </summary> | |
36 /// <typeparam name="T"></typeparam> | |
37 /// <param name="value">The value.</param> | |
38 /// <param name="minValue">The minimum value.</param> | |
39 /// <param name="maxValue">The maximum value.</param> | |
40 /// <param name="comparer">An optional comparer to be used instead of the types default comparer.</param> | |
41 /// <returns> | |
42 /// <c>true</c> if the specified value is between min and max; otherwise, <c>false</c>. | |
43 /// </returns> | |
44 /// <example> | |
45 /// var value = 5; | |
46 /// if(value.IsBetween(1, 10)) { | |
47 /// // ... | |
48 /// } | |
49 /// </example> | |
50 public static bool IsBetween<T>(this T value, T minValue, T maxValue, IComparer<T> comparer) where T : IComparable<T> | |
51 { | |
52 comparer = comparer ?? Comparer<T>.Default; | |
53 | |
54 var minMaxCompare = comparer.Compare(minValue, maxValue); | |
55 if (minMaxCompare < 0) | |
56 { | |
57 return ((comparer.Compare(value, minValue) >= 0) && (comparer.Compare(value, maxValue) <= 0)); | |
58 } | |
59 else if (minMaxCompare == 0) | |
60 { | |
61 return (comparer.Compare(value, minValue) == 0); | |
62 } | |
63 else | |
64 { | |
65 return ((comparer.Compare(value, maxValue) >= 0) && (comparer.Compare(value, minValue) <= 0)); | |
66 } | |
67 } | |
68 } | |
69 } |