LINQ的相似用法其实在很多语言中都出现了包括java的stream流,前端的js函数...
1.下面介绍一下如何使用LINQ
1.以官方为例
新建一个类:
using System.Collections.Generic;
namespace ConsoleApp2
{
public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public List<int> Scores;
public override string ToString()
{
return First + Last + ID + Scores;
}
}
}
2.我们需要清楚的知道就是LINQ基本是用于在集合身上的。所以我们需要初始化一个集合,在Program类也就是启动类中,加入一个静态函数方法
private static List<Student> Students = new List<Student>()
{
new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91}}
};
3.其实写法真的和其他的语言没什么差距,为了能够更加快的了解如何使用,我们可以简单的看一下源码:
(1).从where用法开始,可以理解为数据库中的where筛选条件,比较熟java的话其实就是过滤(fileter)有两个参数 :第一个使用了this修饰代表当前对象,第二个是一个Func函数,可以理解为java中的Function函数
public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
现在我需要从集合中筛选学生的scores第一个下标大于90的需求:
代码如下:
//第一种写法
//func函数作为参数
Func<Student, bool> func = (student) =>
{
return student.Scores[0]>90;
};
var enumerable = Students.Where(func).Select(stu=>stu);
Students是初始化的list的对象。然后这里调用了where函数,它需要的参数上面我做了解释。其实说白了我传入的func对象进去,它最终过滤的时候也是调用我的func后面实现的拉布达表达式。这里对Func做个介绍。<>这个说白了就是泛型。然后第一给参数是入参 第二个是返回值类型。可以更简单的理解就是除了最后一个类型,其他都是匿名函数的入参类型。下面是更加简洁的写法:
//第二种写法
//使用匿名函数
var niMing = Students.Where(student => student.Scores[0] > 90).Select(student =>student);
当然还有第三种:
//第三种写法
var third = from student in Students
where student.Scores[0] > 90
select student;
是的。这里的where需要一个func,那么select是同样的原理。
当你明白原理,就自己测试函数吧