Author Topic: Playing with: Collection Expressions  (Read 723 times)

0 Members and 1 Guest are viewing this topic.

gile

  • Gator
  • Posts: 2522
  • Marseille, France
Playing with: Collection Expressions
« on: January 01, 2024, 09:54:51 AM »
Looks like F#
Code - C#: [Select]
  1. > int[] ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  2. > ints[3..]
  3. int[7] { 3, 4, 5, 6, 7, 8, 9 }
  4. > ints[..4]
  5. int[4] { 0, 1, 2, 3 }
  6. > ints[..^2]
  7. int[8] { 0, 1, 2, 3, 4, 5, 6, 7 }

Goodbye Substring() method...
Code - C#: [Select]
  1. > string str = "abcdef";
  2. > str[3..]
  3. "def"
  4. > str[..^1]
  5. "abcde"
  6. > str[2..^2]
  7. "cd"

Merge Sort with Span<T> structure.
Code - C#: [Select]
  1. static Span<T> MergeSort<T>(Span<T> span) where T : IComparable<T>
  2. {
  3.     if (span.Length <= 1)
  4.         return span;
  5.     int middle = span.Length / 2;
  6.     return Merge(MergeSort(span[..middle]), MergeSort(span[middle..]));
  7. }
  8.  
  9. static Span<T> Merge<T>(Span<T> left, Span<T> right) where T : IComparable<T>
  10. {
  11.     int n = left.Length, m = right.Length, i = 0, j = 0, k = 0;
  12.     var result = new T[n + m];
  13.     while (k < result.Length)
  14.     {
  15.         result[k++] = (i == n, j == m) switch
  16.         {
  17.             (true, _) => right[j++],
  18.             (_, true) => left[i++],
  19.             _ => left[i].CompareTo(right[j]) <= 0 ? left[i++] : right[j++]
  20.         };
  21.     }
  22.     return result;
  23. }

Code - C#: [Select]
  1. > List<int> unsorted = [6, 7, 9, 1, 8, 3, 5, 0, 4, 2];
  2. > List<int> sorted = [.. MergeSort([.. unsorted])];
  3. > sorted
  4. List<int>(10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
« Last Edit: January 02, 2024, 03:20:52 AM by gile »
Speaking English as a French Frog