110,536
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 继承IComparer<T>接口,实现同一自定义类型 对象比较
/// </summary>
/// <typeparam name="T">泛用类型</typeparam>
public class Reverser<T> : IComparer<T>
{
private Type type = null;
private string name=string.Empty;
private Direction direction;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="type">进行比较的类类型</param>
/// <param name="name">进行比较对象的属性名称</param>
/// <param name="direction">比较方向(升序/降序)</param>
public Reverser(Type type, string name, Direction direction)
{
this.type = type;
this.name = name;
if (direction != Direction.ASC)
this.direction = direction;
}
//必须实现IComparer<T>的比较方法。
int IComparer<T>.Compare(T t1, T t2)
{
object x = this.type.InvokeMember(this.name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, t1, null);
object y = this.type.InvokeMember(this.name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, t2, null);
if (this.direction != Direction.ASC)
Swap(ref x, ref y);
return (new CaseInsensitiveComparer()).Compare(x, y);
}
//交换操作数
private void Swap(ref object x, ref object y)
{
object temp = null;
temp = x;
x = y;
y = temp;
}
}
/// <summary>
/// 比较的方向,如下:
/// ASC:升序
/// DESC:降序
/// </summary>
public enum Direction
{
/// <summary>
/// 升序
/// </summary>
ASC = 0,
/// <summary>
/// 降序
/// </summary>
DESC,
}
用法:
private List<LaneSatusInfo> outLaneStatusIcon=new List<LaneSatusInfo>();
Reverser<LaneSatusInfo> reverserIcon = new Reverser<LaneSatusInfo>(typeof(LaneSatusInfo), "LaneID", Direction.ASC);
//按车道号对出口的车道图标数据进行升序排列
if (outLaneStatusIcon.Count != 0)
{
outLaneStatusIcon.Sort(reverserIcon);
}
list.RemoveAll(p => p.id == 要删除的id); //删除
list.Sort((p1,p2) => p1.id - p2.id); //排序
class people : IComparable
{
public int Id { get; set; }
public string Name { get; set; }
public int CompareTo(object obj)
{
int result;
try
{
people info = obj as people;
if (this.Id > info.Id)
{
result = 0;
}
else
result = 1;
return result;
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
}
private void button2_Click(object sender, EventArgs e)
{
List<people> PList = new List<people>();
PList.Add(
new people() { Id = 1, Name = "jack" });
PList.Add(new people() { Id = 3, Name = "tom" });
PList.Add(new people() { Id = 2, Name = "soya" });
PList.Sort();
foreach (var item in PList)
{
listBox1.Items.Add(item.Id + ":" + item.Name);
}
}