几种查询方法(lambda Linq Enumerable静态类方式)

时间:2023-03-09 18:35:54
几种查询方法(lambda Linq Enumerable静态类方式)

1.需要一个数据源类:

using System;
using System.Collections.Generic; namespace Linq
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
} public class Data
{
public static List<Student> studentList = new List<Student>()
{
new Student()
{ Name="李四",
Age=
},
new Student()
{
Name="张三",
Age=
}
}; }
}

2.主函数调用类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Linq
{
class Program
{
static void Main(string[] args)
{
LinqTest lin = new LinqTest();
lin.Show();
}
}
}

3.查询方法(重点介绍的)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Linq
{
public class LinqTest
{
public void Show()
{
List<Student> studentList = new List<Student>();//
Console.WriteLine("-----------------foreach方式(1)---------"); foreach (Student item in Data.studentList) ////Data.studentList是数据源
{
if (item.Age > )
{
studentList.Add(item);//将数据源中满足要求的数据填充到指定容器中
}
} //studentList中以填充数据
foreach (Student item in studentList)
{
Console.WriteLine("foreach方式:Name={0},Age={1}", item.Name, item.Age);
} Console.WriteLine("-----------linq方式(2)-------------");
var linq = from s in Data.studentList where s.Age > select s;
foreach (var item in linq)
{
Console.WriteLine("linq方式:Name={0},Age={1}", item.Name, item.Age);
} Console.WriteLine("-----------lambda方式(3)-------------");
// var lambda = Data.studentList.Where(s => s.Age > 18); where可以自动推断类型 扩展方法
var lambda = Data.studentList.Where<Student>(s => s.Age > );
foreach (var item in lambda)
{
Console.WriteLine("lambda方式:Name={0},Age={1}", item.Name, item.Age);
} Console.WriteLine("-------Enumerable静态类方式(4)-----------");
var enm= Enumerable.Where(Data.studentList, s => s.Age > );
foreach (var item in enm)
{
Console.WriteLine("Enumerable静态类方式:Name={0},Age={1}", item.Name, item.Age);
}
} }
}

(3.1)对where扩展方法的理解即学习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Linq
{
public class LinqTest
{
public void Show()
{
Console.WriteLine("-----------lambda方式(3.1)where扩展-------------");
var linqExtend = Data.studentList.WhereExtend(s => s.Age > ); //where可以自动推断类型 扩展方法 foreach (var item in linqExtend)
{
Console.WriteLine("lambda方式(3.1)where扩展:Name={0},Age={1}", item.Name, item.Age);
}
}
}
/// <summary>
/// where的扩展方法
/// </summary>
public static class LinqExtend
{
public static IEnumerable<T> WhereExtend<T>(this IEnumerable<T> tList,Func<T,bool> func) where T : Student// func:用于测试每个元素是否满足条件的函数。
{
var Linq = from s in tList where func(s) select s;
return Linq;
} }
}