MVC ---- 理解学习Func用法
//Func用法
public static class FuncDemo{
public static void TestFunc(){
//数据源
List<User> usList = Five.GetUserList();
//Select是Func的委托
//public delegate TResult Func<in T,out TResult>(T arg); //out TResult可以自定义输出类型,可以有多个输入in T
//usList.Select(new Func<User,TResult>(delegate(User u){
//输出参数,返回值 new Func<User,int> 这里返回int 类型
//}));
//返回int类型的集合
List<int> usAges= usList.Select(new Func<User,int>(
delegate(User u){
return u.Age;
})).ToList();
//输出结果
usAges.ForEach(u=>{Console.WriteLine(u);});
//上面的缩写lambad表达式没有指定数据类型,会自行推断 (返回Age列,个人理解)
List<int> usAges= usList.Select(u=>{
return u.Age;
}).ToList();
------------------------------------------
//新的类型 ,Employee 是返回值
List<Employee> els = usList.Select(new Func<User,Employee>(delegate(User u){
Employee e = null;
if(u.Age > 12){
e.name = u.Name;
e.Phone = u.Phone;
e.Salary = 80000;
}else{
return null;
}
return e;
})).ToList();
//==========--------------begin上面缩写-----------========
List<Employee> els = usList.Select(
GetEmployeFromUsers //这里满足委托条件
).ToList();
//处理els集合
els.ForEach(e=>{
if(e!=null)
{
Console.WriteLine(e.Name+""+e.Phone);
}
});
}
//从新定义个方法(这里处理比较复杂,就单独写成一个方法)
public static Employee GetEmployeFromUsers(User u){
Employee e = new Employee();
if(u.Age > 12){
e.Name = u.Name;
e.Phone = u.Phone;
e.Salary = u.Salary;
}else{
return null;
}
return e;
}
}
//一个实体类
public class Employee{
public string name{get;set;}
public string Phone{get;set;}
public decimal Salary{get;set;}
}
//==========--------------end上面缩写-----------========