.net FrameWork 框架博大精深,用着忘着,计划对自己能够想到知识点梳理一下,此篇是对自定义排序的理解:
class Program { static void Main(string[] args)
{
Random random = new Random();
ClassA[] arr = new ClassA[];//数组还有IEnumerator是没有实现Sort的,List实现了 Console.WriteLine("Source Value:");
for (int i = ; i < ; i++)
{
arr[i] = new ClassA(random.Next(), random.Next());
Console.WriteLine(arr[i].XY);
}
Console.WriteLine();
Console.WriteLine("Source ToList Value:");
var list = arr.ToList();
for (int i = ; i < ; i++)
{
Console.WriteLine(list[i].XY);
}
Console.WriteLine();
Console.WriteLine("Source ToList Sort Value:");
list.Sort();
for (int i = ; i < ; i++)
{
Console.WriteLine(list[i].XY);
}
Console.WriteLine();
Console.WriteLine("Source ToList Compare Value:");
list.Sort(new ClassAComparer());//简单实现降序
//等同于 list.Sort((x,y)=>-x.CompareTo(y));//实现降序
for (int i = ; i < ; i++)
{
Console.WriteLine(list[i].XY);
} Console.WriteLine();
Console.WriteLine("Priority Source Value:");
//在一些常用场景经常会有优先级的概念,针对有优先级的排序,可以参照如下:
//Tuple<int,int> ,Item1的优先级大于Item2的优先级
List<Tuple<int, int>> list_priority = new List<Tuple<int, int>>();
for (int i = ; i < ; i++)
{
Tuple<int, int> xy = new Tuple<int, int>(random.Next(), random.Next());
list_priority.Add(xy);
Console.WriteLine(string.Format("{{X:{0},Y:{1}}}", xy.Item1, xy.Item2));
} Console.WriteLine();
Console.WriteLine("Priority Source Sort Value:");
list_priority.Sort((x, y) =>
{
if (x.Item1 > y.Item1)
return ;
else if (x.Item1 == y.Item1)
return x.Item2 - y.Item2;
else
return -;
});
for (int i = ; i < ; i++)
{
Console.WriteLine(string.Format("{{X:{0},Y:{1}}}", list_priority[i].Item1, list_priority[i].Item2));
}
Console.ReadKey(); //其实还有一些场景,会用到权重的概念,尤其是针对一些客户定级别时候,这个时候的排序,建议权重高的,
//排序时候去平方,或者倍乘等方式,涉及到权重的,都是玄之又玄,出来的结果大致满意就很棒了。。。
}
} class ClassA:IComparable<ClassA>//定义在对象上的自定义排序,这里引用泛型,不需类型转换
{
public ClassA(int x, int y)
{
this.X = x;
this.Y = y;
}
public int X { get; set; } public int Y { get; set; } public string XY
{
get
{
return string.Format("{{X:{0},Y:{1}}}", X, Y);//C#打印大括号,左大括号{{,有大括号}}
}
} public int CompareTo(ClassA other)
{
int val = X + Y;
int otherVal = other.X + other.Y;
return val - otherVal;//三种结果 1,-1,0分别是大,小,相等
}
} class ClassAComparer : IComparer<ClassA>//单独定义的排序规则
{
public int Compare(ClassA x, ClassA y)
{
int valX = x.X + x.Y;
int valY = y.X + y.Y;
return valY - valX;
}
}
在做一个对象集的比较时候,用到不同的比较规则,这个时候,用一个封装,如下:
public class Compare<T> : IEqualityComparer<T>
{
private Func<T,T,bool> _equalsComparer; public Compare(Func<T,T,bool> equalsComparer)
{
this._equalsComparer = equalsComparer;
} public bool Equals(T x, T y)
{
if (null != this._equalsComparer)
return this._equalsComparer(x, y);
else
return false;
} public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}