C# Func入门二
这一篇是继续上篇的,只不过这篇用的数据是个对象。
一、这边要构建的数据如下:
1.User类
public class User { public int identity { get; set; } public string name { get; set; } public string city { get; set; } public string birth { get; set; } public User(int id, string n, string c, string bir) { identity = id; name = n; city = c; birth = bir; } }
2.返回全部测试的User数据如下
public static User[] GetAllUsers() { User[] users = { new User(1, "John", "London", "2001-04-01"), new User(2, "Lenny", "New York", "1997-12-11"), new User(3, "Andrew", "Boston", "1987-02-22"), new User(4, "Peter", "Prague", "1936-03-24"), new User(5, "Anna", "Bratislava", "1973-11-18"), new User(6, "Albert", "Bratislava", "1940-12-11"), new User(7, "Adam", "Trnava", "1983-12-01"), new User(8, "Robert", "Bratislava", "1935-05-15"), new User(9, "Robert", "Prague", "1998-03-14"), }; return users; }
二、例子八:筛选出住在"Bratislava"的人。
//8.c# Func filter array static void FunFilterArray() { var users = GetAllUsers(); var city = "Bratislava"; Func<User, bool> livesIn = e => e.city == city; var res = users.Where(livesIn); foreach (var t in res) { Console.WriteLine(t.name); } }
测试结果如下:
三、例子九:筛选出年龄大于60岁的人。
//9.c# Func filter by age public static int GetAge(User user) { var dob = DateTime.Parse(user.birth); return (int)Math.Floor((DateTime.Now - dob).TotalDays / 365.250); } public static void FuncFilterByAge() { var users = GetAllUsers(); var age = 60; Func<User, bool> olderThan60 = e => GetAge(e) > age; var res = users.Where(olderThan60); foreach (var e in res) { Console.WriteLine(e.name); } }
四、例子十:Func也可以当作一个参数。(可以与例子八的写法比较一下)
//10.c# pass Func as parameter public static void ShowOutPut(User[] users, Func<User, bool> condition) { var data = users.Where(condition); foreach (var person in data) { Console.WriteLine(person.name); } } public static void FuncAsParameter() { var users = GetAllUsers(); ShowOutPut(users, r => r.city == "Bratislava"); }
测试结果如下:
五、例子十一:我们可以通过链接来编写Funcs。
//11.C# Func compose.(We can compose Funcs by chaining.) public static void FuncChaining() { var vals = new int[] { 1, 2, 3, 4, 5 }; Func<int, int> inc = e => e + 1; Func<int, int> cube = e => e * e * e; var res = vals.Select(inc).Select(cube); foreach (var e in res) { Console.WriteLine(e); } }
测试结果如下:
六、网址参考
https://zetcode.com/csharp/func/
本地代码在CSharpBasic\FuncTutorial
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/keeplearningandsharing/p/16670270.html