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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| static void Main(string[] args)
{
Random r = new Random(0);
Group<Personne> group = new Group<Personne>();
for (int i = 0; i < 10; i++)
{
group.Add(new Personne(r.Next(100), r.Next(100)));
}
// Sort by default
group.Sort();
// Sort by Field
group.Sort(Field.Age);
}
public enum Field
{
ID,
Age
}
/// <summary>
/// Demo classe Personne
/// </summary>
public class Personne
{
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public Personne(int id, int age)
{
this.ID = id;
this.Age = age;
}
}
/// <summary>
/// Custom collection with support of multiple sort expression
/// </summary>
/// <typeparam name="TObject"></typeparam>
public class Group<TObject> : List<TObject> where TObject : Personne
{
public Group()
{
// Default expression is ID
this.SortExpression = Field.ID;
}
private Field sortExpression;
public Field SortExpression
{
get { return sortExpression; }
set { sortExpression = value; }
}
public void Sort(Field expression)
{
this.SortExpression = expression;
this.Sort();
}
public new void Sort()
{
Console.WriteLine("Sort by " + this.SortExpression);
this.Sort(new Comparison<TObject>(this.Compare));
}
public int Compare(TObject x, TObject y)
{
return this.CompareImpl(x, y);
}
protected virtual int CompareImpl(TObject x, TObject y)
{
switch (this.SortExpression)
{
case Field.ID:
return x.ID.CompareTo(y.ID);
case Field.Age:
return x.Age.CompareTo(y.Age);
default:
throw new Exception("Invalid Field");
}
}
} |