使用ArrayList集合对字符串类型和封装类进行排序
这是封装类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayList的排序
{
class Person :IComparable
{
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public int Age
{
get;
set;
}
public int CompareTo(object obj)
{
Person p = obj as Person;
//需要特别注意对null的处理,微软默认null最小,所以直接返回-1就ok
if (p!=null)
{
return this.Name.Length - p.Name.Length;
}
return -1;
}
public Person(string name,int age)
{
this.Name = name;
this.Age = age;
}
//对ToString方法进行重写,方便打印
public override string ToString()
{
return this.Name + this.Age;
}
}
}
这是主类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayList的排序
{
class Program
{
static void Main(string[] args)
{
#region arrayList对字符串的排序
//ArrayList arrayList = new ArrayList();
//arrayList.Add(new string(new char[] { 'a', 'b', 'c' }));
//arrayList.Add("abd");
//arrayList.Add("xyz");
//arrayList.Add("xxx");
//arrayList.Sort();
//for (int i = 0; i < arrayList.Count; i++)
//{
// Console.WriteLine(arrayList[i]);
//}
//Console.ReadKey();
#endregion
#region 使用arraylist进行对封装类的排序。
ArrayList arrayList = new ArrayList();
Person p1 = new Person("刘霞", 18);
Person p2 = new Person("liuliuliu", 19);
Person p3 = new Person("liuliu", 23);
arrayList.Add(p1);
arrayList.Add(p2);
arrayList.Add(p3);
arrayList.Add(null);
arrayList.Add(null);
//不使用比较器的重载方法
//arrayList.Sort();
//使用比较器的重载方法
arrayList.Sort(new PersonSortByName());
for (int i = 0; i < arrayList.Count; i++)
{
Console.WriteLine(arrayList[i]);//在Person类中进行了对ToString方法的重写,否则返回的是类名。
}
Console.ReadKey();
#endregion
}
}
}
这是比较器类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayList的排序
{
//实现了IComparer的接口的类是一个比较器,是ArrayList集合中Sort方法的一个重载方法。
//比较器类
class PersonSortByName : IComparer
{
public int Compare(object x, object y)
{
Person p1 = x as Person;
Person p2 = y as Person;
//需要特别注意对null的处理,微软默认null最小,所以直接返回-1就ok
if(p1!=null && p2 != null)
{
return p1.Name.Length - p2.Name.Length;
}
else
{
return -1;
}
}
}
}