1、person类
public class Person
{
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 名字
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public bool Sex { get; set; }
public Person(int age, string name, bool sex)
{
Age = age;
Name = name;
Sex = sex;
}
/// <summary>
/// 重写Tostring方法,实现要显示内容的格式
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("年龄:{0},性名:{1},性别:{2}", Age.ToString(), Name, Sex ? "男":"女");
}
}
2、窗体
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Person> person = new List<Person>();
private void Form1_Load(object sender, EventArgs e)
{
#region 给list添加成员
person.Add(new Person(18, "光哥", true));
person.Add(new Person(28, "兵哥哥", true));
person.Add(new Person(22, "凡哥", true));
person.Add(new Person(22, "平平", false));
person.Add(new Person(23, "小蘑菇", false));
person.Add(new Person(23, "小破颖", false));
person.Add(new Person(28, "金泽", true));
person.Add(new Person(26, "慧鹏", true));
person.Add(new Person(24, "招子", true));
#endregion
}
/// <summary>
/// 英文排序与数字排序, Lambda 表达式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
showContent.Text += "初始化序列:\r\n";
ShowList(person);
showContent.Text += "\r\n按照年零从大到小排\r\n";
person.Sort((x, y) => x.Age < y.Age ? -1 : 0);
ShowList(person);
showContent.Text += "\r\n按照姓名首字母升序排序\r\n";
person.Sort((x, y) => x.Name.CompareTo(y.Name));
ShowList(person);
}
/// <summary>
/// 显示内容
/// </summary>
/// <param name="list"></param>
private void ShowList(List<Person> list)
{
for (int i = 0; i < list.Count; i++)
{
showContent.Text += list[i].ToString() + "\r\n";
}
}
private void button2_Click(object sender, EventArgs e)
{
showContent.Text+= "\r\n**找出Name=\"金泽\"的人:\r\n";
showContent.Text += person.Find((Person p) =>p.Name == "金泽").ToString();
showContent.Text += "\r\n\r\n**找出第一个男孩:";
showContent.Text +=person.Find((Person p)=>p.Sex==true).ToString();
showContent.Text += "\r\n\r\n**找出所有男孩:";
showContent.Text += person.FindAll((Person p) => p.Sex == true).ToString();
List<Person> a = new List<Person>();
showContent.Text += "\r\n\r\n**判断“小破颖”是否存在:\r\n";
showContent.Text += person.Exists((Person p) => p.Name == "小破颖" ? true : false).ToString();
}
}
3、list的sort方法
list中存了很多条记录或者很多个对象, 此时我们可以根据对象的某些属性进行排序,它提供了一个数字的排序,一个字符串拼音排序:
4、list的find,findAll,exists的用法