loading
open in
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;

class MainClass {
  public static void Main (string[] args) {
    var personList = new List<Person>
    {
      new Person {Name="Fatih", Age=31 },
      new Person {Name ="Alice", Age=2 },
      new Person {Name="Mehmet", Age=30 },
      new Person {Name="Eric", Age = 28  },
      new Person {Name="Tarik", Age = 22  }
    };

    personList.Sort(new Sorter(p => p.Name, false));

    foreach(Person person in personList)
    {
      Console.WriteLine($"{person.Name} {person.Age}");
    }
  }

  public class Person
  {
    public string Name { get; set; }
    public int Age { get; set; }
  }

  public class Sorter : IComparer<Person>
  {
    private readonly Func<Person, IComparable> _fieldComparer;
    private readonly bool _isAscending;

    public Sorter(Func<Person, IComparable> fieldComparer, bool isAscending = true)
    {
      _fieldComparer = fieldComparer;
      _isAscending = isAscending;
    }

    public int Compare(Person x, Person y)
    {
      if (_isAscending)
        return _fieldComparer(x).CompareTo(_fieldComparer(y));
      else
        return _fieldComparer(y).CompareTo(_fieldComparer(x));
    }
  }

  public class SortByAge : IComparer<Person>
  {
    private readonly bool _isAscending;

    public SortByAge(bool isAscending = true)
    {
      _isAscending = isAscending;
    }

    public int Compare(Person x, Person y)
    {
      if (_isAscending)
        return x.Age.CompareTo(y.Age);
      else
        return y.Age.CompareTo(x.Age);
    }
  }

  public class SortByName : IComparer<Person>
  {
    private readonly bool _isAscending;

    public SortByName(bool isAscending = true)
    {
      _isAscending = isAscending;
    }

    public int Compare(Person x, Person y)
    {
      if (_isAscending)
        return x.Name.CompareTo(y.Name);
      else
        return y.Name.CompareTo(x.Name);
    }
  }
}