一、Linq基本用法
namespace CSharpAdvancedLinq
{
/// <summary>
/// LINQ(Language Integrated Query)即语言集成查询--用来查询一些操作类库
/// 1.LINQ to Object 主要负责对象的查询
/// 2.LINQ to XML 主要负责XML的查询
/// 3.LINQ to ADO.NET 主要负责数据库的查询
/// linq核心就是对数据源的操作
/// 学linq另外知识点非常重要--扩展方法
/// </summary>
class LinqTest
{
public void Show()
{
List<Student> StuList = new List<Student>()
{
new Student
{
Id=1,
Name="Ant编程",
Age=1,
Address="杭州"
},
new Student
{
Id=2,
Name="Ant编程2",
Age=2,
Address="杭州"
},
new Student
{
Id=3,
Name="Ant编程3",
Age=3,
Address="杭州"
}
};//数据源
{
Console.WriteLine("-------------普通查询------------");
foreach(var item in StuList)
{
if(item.Age<=20)
{
Console.WriteLine($"Name:{item.Name}Id:{item.Id}Age:{item.Age}");
}
}
}
{
Console.WriteLine("-------------扩展查询(linq)------------");
var list= StuList.Where(s => s.Age <= 20);//s为参数
foreach(var item in list)
{
Console.WriteLine($"Name:{item.Name}Id:{item.Id}Age:{item.Age}");
}
}
{
Console.WriteLine("-------------关键词的方式(linq)------------");
var list = from s in StuList
where s.Age <= 20
select s;
foreach (var item in list)
{
Console.WriteLine($"Name:{item.Name}Id:{item.Id}Age:{item.Age}");
}
}
{
Console.WriteLine("-------------关键词的方式(linq--自定义)------------");
var list = StuList.AntWhere(s => s.Age <= 20);//s为参数
foreach (var item in list)
{
Console.WriteLine($"Name:{item.Name}Id:{item.Id}Age:{item.Age}");
}
}
}
}
}
namespace CSharpAdvancedLinq
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}
二、自定义Linq
namespace CSharpAdvancedLinq
{
//静态类里的静态方法——扩展方法
public static class ExterndMethod
{
public static List<Student> AntWhere(this List<Student>
resource,Func<Student,bool> func)
{
List<Student> list = new List<Student>();
foreach(var item in resource)
{
if(func.Invoke(item))
{
list.Add(item);
}
}
return list;
}
}
}