Last active
June 10, 2021 13:37
-
-
Save ZacharyPatten/3b7d7d63bc5188d3f7c863639f14765d to your computer and use it in GitHub Desktop.
Custome Range Syntax in C# for fun...
This file contains 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
using System; | |
using System.Collections.Generic; | |
using static Statics; | |
class Program | |
{ | |
static void Main() | |
{ | |
foreach (int i in -6 -to- -4) | |
{ | |
Console.WriteLine(i); | |
} | |
foreach (long l in -2 -to- 2) | |
{ | |
Console.WriteLine(l); | |
} | |
foreach (char c in 'a'-to-'e') | |
{ | |
Console.WriteLine(c); | |
} | |
string[] names = { "Sally", "Bob", "Joe", "Eric", "Patty" }; | |
foreach (string s in names.Where("Allen"-tᴏ-"Kevin")) | |
{ | |
Console.WriteLine(s); | |
} | |
} | |
} | |
#region Nothing To See Here | |
public struct To1<T> | |
{ | |
public static To2<T> operator -(T a, To1<T> to) => new() { _a = a }; | |
} | |
public struct To2<T> | |
{ | |
internal T _a; | |
public static Range<T> operator -(To2<T> to, T b) => new() { _a = to._a, _b = b }; | |
} | |
public struct Range<T> | |
{ | |
internal T _a; | |
public T A => _a; | |
internal T _b; | |
public T B => _b; | |
} | |
public static class Extensions | |
{ | |
public static IEnumerator<int> GetEnumerator(this Range<int> range) | |
{ | |
for (int i = range.A; i <= range.B; i++) | |
{ | |
yield return i; | |
} | |
} | |
public static IEnumerator<char> GetEnumerator(this Range<char> range) | |
{ | |
for (char i = range.A; i <= range.B; i++) | |
{ | |
yield return i; | |
} | |
} | |
public static IEnumerable<string> Where(this IEnumerable<string> strings, Range<string> range) | |
{ | |
foreach (string s in strings) | |
{ | |
if (s.CompareTo(range.A) >= 0 && s.CompareTo(range.B) <= 0) | |
{ | |
yield return s; | |
} | |
} | |
} | |
} | |
public static class Statics | |
{ | |
public readonly static To1<int> to = default; | |
public readonly static To1<string> tᴏ = default; | |
} | |
#endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment