1 using System;
2 using System.Collections.Generic;
3 using System.Reflection;
4
5 namespace Sorting
6 {
7 public class CommontSortGenerics<T> : IComparer<T>
8 {
9 private string _column;
10 private SortEnum _sort = SortEnum.Asc;
11
12 public CommontSortGenerics(string column, SortEnum sort)
13 {
14 _column = column;
15 _sort = sort;
16 }
17 #region IComparer<T> Members
18
19 public int Compare(T x, T y)
20 {
21 if (x == null && y == null)
22 {
23 return 0;
24 }
25 else if (x == null && y != null)
26 {
27 return (this._sort == SortEnum.Asc) ? -1 : 1;
28 }
29 else if (x != null && y == null)
30 {
31 return (this._sort == SortEnum.Asc) ? 1 : -1;
32 }
33 else
34 {
35 Type xType = x.GetType();
36 Type yType = y.GetType();
37
38 PropertyInfo xInfo = xType.GetProperty(_column,
39 BindingFlags.DeclaredOnly |
40 BindingFlags.Default |
41 BindingFlags.GetProperty |
42 BindingFlags.Public |
43 BindingFlags.Instance);
44 PropertyInfo yInfo = yType.GetProperty(_column,
45 BindingFlags.DeclaredOnly |
46 BindingFlags.Default |
47 BindingFlags.GetProperty |
48 BindingFlags.Public |
49 BindingFlags.Instance);
50
51 object xVal = xInfo.GetValue(x, null);
52 object yVal = yInfo.GetValue(y, null);
53
54 return (this._sort == SortEnum.Asc) ?
55 ((IComparable)xVal).CompareTo(yVal) :
56 ((IComparable)yVal).CompareTo(xVal);
57
58 }
59 }
60
61 #endregion
62 }
63 }