创建一个集合,里面有10个圆对象,根据面积对此集合排序 lamba表达式排序
使用接口实现策略排序,分别对一个装有10个矩形的长,面积,周长进行排序
public static void Task01()
{
List<Shape> shaps = new List<Shape>();
Random random = new Random();
for (int i = 0; i < 10; i++)
{
shaps.Add(new Circle(random.Next(1,20)));
}
//lambe表达式排序,默认升序排序
shaps.Sort((x,y)=> { return (x.GetArea() - y.GetArea()); });
foreach (var item in shaps)
{
Console.WriteLine(item);
}
}
//父类,提供字段和方法
namespace Examination
{
//abstract 抽象
//抽象类是无法进行实例化的
abstract class Shape
{
public abstract int GetLength();
public abstract int GetArea();
public override string ToString()
{
return string.Format("面积:{0}",GetArea());
}
}
}
//子类,继承
namespace Examination
{
class Circle : Shape
{
private float radius;
public Circle(float radius)
{
this.Radius = radius;
}
public float Radius
{
get
{
return radius;
}
set
{
radius = value;
}
}
public override int GetArea()
{
return (int)(Math.Pow(Radius, 2) * Math.PI);
}
public override int GetLength()
{
return (int)(2 * Radius * Math.PI);
}
}
}
策略排序就是对接口和冒泡排序的组合,
static void PrintStudentArr(Oblong[] obl)
{
for (int i = 0; i < obl.Length; i++)
{
Console.WriteLine(obl[obl.Length-1-i]);
}
}
static void Sort(Oblong[] obl, IMyCompare com)
{
for (int i = 0; i < obl.Length - 1; i++)
{
for (int j = 0; j < obl.Length - 1 - i; j++)
{
if (com.Compare(obl[j + 1], obl[j]))
{
Oblong stu = obl[j + 1];
obl[j + 1] = obl[j];
obl[j] = stu;
}
}
}
}
class Program
{
static void Main(string[] args)
{
Random random = new Random();
Oblong[] obl = new Oblong[10];
for (int i = 0; i < obl.Length; i++)
{
obl[i] = new Oblong (random.Next(1,100),random.Next(1,100));
}
Console.WriteLine("----------------------");
IMyCompare com = new CompareByArea();
Sort(obl, com);
PrintStudentArr(obl);
Console.WriteLine("--------------");
com = new CompareByOblong();
Sort(obl, com);
PrintStudentArr(obl);
}
}
interface IMyCompare
{
bool Compare(object obj1, object obj2);
}
class CompareByOblong : IMyCompare
{
public bool Compare(object obj1, object obj2)
{
return (obj1 as Oblong).Getlength() > (obj2 as Oblong).Getlength() ? true : false;
}
}
class CompareByArea : IMyCompare
{
public bool Compare(object obj1, object obj2)
{
return (obj1 as Oblong).GetArea()> (obj2 as Oblong).GetArea() ? true : false;
}
}
class Oblong : Rectangle
{
private int mlong;
private int wide;
public Oblong(int mlong, int wide)
{
this.Mlong = mlong;
this.Wide = wide;
}
public int Mlong
{
get
{
return mlong;
}
set
{
mlong = value;
}
}
public int Wide
{
get
{
return wide;
}
set
{
wide = value;
}
}
public override int GetArea()
{
return (Wide + mlong) * 2;
}
public override int Getlength()
{
return Wide * Mlong;
}
}
abstract class Rectangle
{
public abstract int Getlength();
public abstract int GetArea();
public override string ToString()
{
return string.Format("面积{0},周长{1}", GetArea(), Getlength());
}
}