public bool public class Collection<T>:CollectionBase
{
public Collection()
{
//
// TODO: Add constructor logic here
//
}
public T this[int index]
{
get { return (T)this.List[index]; }
set { this.List[index] = value; }
}
public int IndexOf(T item)
{
return this.List.IndexOf(item);
}
public int Add(T item)
{
return this.List.Add(item);
}
public void Remove(T item)
{
this.List.Remove(item);
}
public void CopyTo(Array array, int index)
{
this.List.CopyTo(array, index);
}
public void AddRange(Collection<T>
collection)
{
for (int i = 0; i < collection.Count; i++)
{
this.List.Add(collection[i]);
}
}
public void AddRange(T[] collection)
{
this.AddRange(collection);
}
Contains(T item)
{
return this.List.Contains(item);
}
public void Insert(int index, T item)
{
this.List.Insert(index, item);
}
}
Now, we will add a sort method to this generic collection object. I
will declare an enumeration called SortOrder to indicate the sort direction. We will use IComparer interface to implement sort for this collection object.
public enum SortOrder
{
ASC,
DSC
}
class GenericComparer : IComparer
{
private string _property;
private SortOrder _order;
public GenericComparer(string Property,SortOrder
Order)
{
this._property = Property;
this._order = Order;
}
//Sort
public int Compare(object obj1, object obj2)
{
int returnValue;
Type type = obj1.GetType();
PropertyInfo propertie1 =
type.GetProperty(_property);
Type type2 = obj2.GetType();
PropertyInfo propertie2 =
type2.GetProperty(_property);
object finalObj1 = propertie1.GetValue(obj1,
null);
object finalObj2 = propertie2.GetValue(obj2,
null);
IComparable Ic1 = finalObj1 as IComparable;
IComparable Ic2 = finalObj2 as IComparable;
if (_order == SortOrder.ASC)
{
returnValue = Ic1.CompareTo(Ic2);
}
else
{
returnValue = Ic2.CompareTo(Ic1);
}
return returnValue;
}
}
|