1.首先需要一个集合用来测试:
//定义一个集合要用的类:
public class People
{
public People(string name, string sex, int age,decimal height)
{
this.Name = name;
this.Sex = sex;
this.Age = age;
this.Height = height;
}
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public decimal Height { get; set; }
public string ToString(string format)
{
return ToString(format);
}
}
//制造几条测试数据:
List<People> list = new List<People>();
list.Add(new People("ymw", "男", 22, 170m));
list.Add(new People("Lily", "女", 21, 160m));
list.Add(new People("xj", "女", 20, 158m));
list.Add(new People("Lucy", "女", 23, 166m));
list.Add(new People("MM", "女", 18, 168m));
2.Linq特性示例一:
//筛选
List<People> lists = list.FindAll(
delegate(People p)
{
return p.Sex == "女";
});
//排序(根据类型)
lists.Sort(
delegate(People p1, People p2)
{
return p1.Name.CompareTo(p2.Name);
});
foreach (People item in lists)
{
this.txt.Text += item.Name + "~" + item.Age + "~" + item.Sex+"~"+item.Height + "\r\n";
}
//如图测试结果:过滤了性别为男的人并按照名称排序↓
3.Linq特性示例二:
//Where、Select、OrderByDescending 用法:Where、Select用来帅选过滤;OrderByDescending是按降序排列
IEnumerable<People> lists = list.Where(
delegate(People p)
{
return p.Sex == "女";
}).OrderByDescending( //OrderBy
delegate(People p)
{
return p.Height;
}).Select(
delegate(People p)
{
return p;
});
foreach (People item in lists)
{
this.txt.Text += item.Name + "~" + item.Age + "~" + item.Sex + "~" + item.Height + "\r\n";
}
// var lists2 = list.Where(p => p.Sex == "女" || p.Sex == "男").OrderBy(p => p.Height).Select(p => p);
//如图测试结果:过滤了性别为男的人并按照身高降序排序↓
4.Linq特性示例三:
// λ表达式
IEnumerable<People> lists = list.Where(p => p.Sex == "女").OrderByDescending(p => p.Height).Select(p => p);
foreach (People item in lists)
{
this.txt.Text += item.Name + "~" + item.Age + "~" + item.Sex + "~" + item.Height + "\r\n";
}
//测试结果如上图实例二:过滤了性别为男的人并按照身高降序排序↓
5.Linq特性示例四:
var lists = (from p in list
where p.Sex == "女"
orderby p.Age ascending, p.Height
select p).Take(4); //Take()取前几条记录
foreach (People item in lists)
{
this.txt.Text += item.Name + "~" + item.Age + "~" + item.Sex + "~" + item.Height + "\r\n";
}
//测试结果如下图,按年龄排序且取前四条记录↓