LambdaLinq
大约 19 分钟约 5712 字
LambdaLinq
Lmbada前世今生
_ = new List<int>().Where(c => c == 1);
// => { }
new LambdaShow().Show();
{
public delegate void NoReturnNoParaOutClass();
public delegate void GenericDelegate<T>();
public class LambdaShow
{
public delegate void NoReturnNoPara();
public delegate void NoReturnWithPara(int x, string y);//1 声明委托
public delegate int WithReturnNoPara();
public delegate string WithReturnWithPara(out int x, ref int y);
public void Show()
{
//Lambda前世今生;
{
//.Netframework1.0/1.1时代
int j = 0;
NoReturnNoPara method = new NoReturnNoPara(DoNothing);
NoReturnWithPara method1 = new NoReturnWithPara(Study);
method1.Invoke(123, "Richard");
}
//.NetFramework2.0 匿名方法 增加了一个delegate关键字,可以访问到除了参数以外的局部变量
int i = 0;
{
NoReturnWithPara method = new NoReturnWithPara(delegate (int x, string y)
{
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(i);
});
}
//.NetFramework3.0 去掉delegate关键了,在参数的后增加了一个=> goes to
{
NoReturnWithPara method = new NoReturnWithPara((int x, string y) =>
{
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(i);
});
}
{
//.NetFramework3.0 后期,去掉了匿名方法红的参数类型--为什么可以去掉? 语法糖:编译器提供的便捷功能;可以推导出类型的参数
NoReturnWithPara method = new NoReturnWithPara((x, y) =>
{
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(i);
});
}
{
//如果匿名方法体中只有一行代码,可以省略方法体的大括号;
NoReturnWithPara method = new NoReturnWithPara((x, y) => Console.WriteLine(x));
NoReturnWithPara method1 = (x, y) => Console.WriteLine(x);
//Lambada
}
{
//一个参数的时候;如果只有一个参数---参数的小括号也可以省略掉
Action<string> method = s => Console.WriteLine("欢迎大家进阶学习");
method.Invoke("牧羊人。。");
}
{
//如果有返回值? 如果lambda表达式中只有一行代码,且有返回值,可以省略return;
Func<string> func1 = new Func<string>(() =>
{
return "";
});
Func<string> func2 = () =>
{
return "";
};
Func<string> func3 = () => "";
Func<string> func = () => "黄大仙";
Func<int, string> func5 = i => i.ToString();
}
}
private void DoNothing()
{
//如果要在这里调用变量j
Console.WriteLine("This is DoNothing");
}
private void Study(int id, string name)
{
Console.WriteLine($"{id} {name} 学习.Net");
}
}
}
匿名类
{
Console.WriteLine("*****************匿名类**************");
Student student = new Student()
{
Id = 1,
Name = "Nochat",
Age = 25,
ClassId = 2
};
student.Study();
Console.WriteLine(student.Id);
Console.WriteLine(student.Name);
//匿名类--new 一个对象的手,也不需要名称了
object model = new//3.0
{
Id = 1,
Name = "Nochat",
Age = 25,
ClassId = 2
};
//无法访问属性值
// Console.WriteLine(model.Id); //为什么?因为C#是强类型语言,object是在编译时确定类型; 因为Object没有这个属性;
//Console.WriteLine(model.Name);
//dynamic避开编译器检查 (4.0) .NETFramework
//(动态类型),可以避开编译器的检查
dynamic dModel = new// dynamic可以便可编译器的检查,运行时检查
{
Id = 1,
Name = "Nochat",
Age = 25,
ClassId = 2
};
dModel.Id = 134;
// dModel.abccc = 1234; //也不报错了---实例中其实是没有这个属性的;
Console.WriteLine(dModel.Id);
Console.WriteLine(dModel.Name);
//Console.WriteLine(dModel.Js);// 会报异常
//var 语法糖 可以理解为弱类型;不确定类型;
Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
var model1 = new //1.不能声明方法 2.不能给属性重新赋值 只能在初始化的时候,给定一个值;
{
Id = 1,
Name = "Nochat",
Age = 25,
ClassId = 2
};
Console.WriteLine(model1.Id); //var 定义的匿名类,可以访问存在的属性值;
Console.WriteLine(model1.Name);
//Console.WriteLine(model1.Js);
// model1.Id = 3; // 属性是只读,不能设置值;
Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
int i2 = 2;
var i1 = 1;//var就是个语法糖,由编译器自动推算
var s = "Richard";
//var strnull = null; //编译器不允许;
// var aa;//var声明的变量必须初始化,必须能推算出类型
//也不允许作为方法的参数类型
////1 var 配合匿名类型使用
////2 var 偷懒,复杂类型的使用
////3 在不知道具体是什么类型的时候就可以使用var 来声明;
//缺陷:个人认为,在代码阅读的时候不是很方便;
//建议大家在写代码的时候,尽量明确类型;
var i = 13;
var j = "";
var mode = new { };
}
{
/// <summary>
/// 学生实体
/// </summary>
public class Student
{
public int Id { get; set; }
public int ClassId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
private string Decription { get; set; }
public void Study()
{
Console.WriteLine("{0} {1}跟着老师学习.net高级开发", this.Id, this.Name);
}
public void StudyFramework()
{
Console.WriteLine("{0} {1}跟着老师学习如何做一名架构师。。。", this.Id, this.Name);
}
public void StudyFullStack()
{
Console.WriteLine("{0} {1}跟着老师学习全栈开发。。。", this.Id, this.Name);
}
}
/// <summary>
/// 班级实体
/// </summary>
public class Class
{
public int Id { get; set; }
public string ClassName { get; set; }
}
}
扩展方法
{
Student student = new Student()
{
Id = 123,
Name = "一叶知秋",
Age = 25,
ClassId = 1
};
student.Study();//调用方法
student.StudyFrameworkClass();
Console.WriteLine("****************************");
MethodExtension.StudyFramework(student);
student.StudyFramework(); //在这里的调用,就像是调用实例方法一样
int i = 0;
i.IntToString();
i.ToInt();
i.GenericeExtend<int>();
string str = "高级语法";
str.GenericeExtend<string>();
str.ToInt();
object oInstanc = "Richard";
oInstanc.GenericeExtend<object>();
oInstanc.ToInt();
string customstring = "欢迎大家来到高级班";
string strResult = customstring.FormetString();//不给length值,就默认为5
string strResult1 = customstring.FormetString(6);
}
{
/// <summary>
/// 扩展方法
/// </summary>
public static class MethodExtension
{
//public static bool isOk(Student student)
//{
// return student.Age < 30;
//}
//static Func<Student, bool> func = isOk;
public static IEnumerable<T> CustomWhereIEnumerable<T>(this IEnumerable<T> studentList, Func<T, bool> func)
{
//List<T> list = new List<T>();
foreach (var item in studentList)
{
Console.WriteLine("*********开始判断*********");
if (func.Invoke(item))
{
//list.Add(item);
yield return item;
}
}
//return list;
}
public static List<T> CustomWhere<T>(this List<T> studentList, Func<T, bool> func)
{
List<T> list = new List<T>();
foreach (var item in studentList)
{
Console.WriteLine("*********开始判断*********");
if (func.Invoke(item))
{
list.Add(item);
//yield return item;
}
}
return list;
}
//来自于Linq的实现:
//public static IEnumerable<TSource> Where<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
//{
// //if (source == null)
// //{
// // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
// //}
// //if (predicate == null)
// //{
// // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate);
// //}
// //Iterator<TSource> iterator = source as Iterator<TSource>;
// //if (iterator != null)
// //{
// // return iterator.Where(predicate);
// //}
// //TSource[] array = source as TSource[];
// //if (array != null)
// //{
// // if (array.Length != 0)
// // {
// // return new WhereArrayIterator<TSource>(array, predicate);
// // }
// // return Empty<TSource>();
// //}
// //List<TSource> list = source as List<TSource>;
// //if (list != null)
// //{
// // return new WhereListIterator<TSource>(list, predicate);
// //}
// //return new WhereEnumerableIterator<TSource>(source, predicate);
//}
public static List<Student> RichardWhere(List<Student> studentList)
{
List<Student> list = new List<Student>();
foreach (var item in studentList)
{
if (item.Age < 30)
{
list.Add(item);
}
}
return list;
}
public static List<Student> RichardWhere1(List<Student> studentList)
{
List<Student> list = new List<Student>();
foreach (var item in studentList)
{
if (item.Name.Length > 2)
{
list.Add(item);
}
}
return list;
}
public static List<Student> RichardWhere2(List<Student> studentList)
{
List<Student> list = new List<Student>();
foreach (var item in studentList)
{
if (item.Id > 1
&& item.Name != null
&& item.ClassId == 1
&& item.Age > 20)
{
list.Add(item);
}
}
return list;
}
public static void StudyFramework(this Student student)
{
//这里是跟着Eleven老师学习如何成为一个架构师
Console.WriteLine($"{student.Id} {student.Name}跟着老师学习如何成为一个高级架构师。。。。");
}
/// <summary>
/// int 类型是可以的
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public static string IntToString(this int i)
{
return i.ToString();
}
///长字符串:如果长度超过30,就把字符串变成前5个字符+‘....’
public static string FormetString(this string oldString, int length = 5)
{
if (string.IsNullOrWhiteSpace(oldString))
{
return string.Empty;
}
else if (oldString.Length <= length)
{
return oldString;
}
else
{
return $"{oldString.Substring(0, length)}...";
}
}
/// <summary>
/// 可以为泛型定义扩展吗?
/// //这个方法是要求返回一个Int
///
/// </summary>
public static int GenericeExtend<T>(this T t)
{
if (t is int)
{
return Convert.ToInt32(t);
}
else if (t is object)
{
}
return 0;
}
public static int ToInt(this object t)
{
if (t is int)
{
return Convert.ToInt32(t);
}
else if (t is object)
{
}
return 0;
}
}
}
Linq to Object
{
List<Student> studentlist = new List<Student>();
studentlist.Where(c => c.Id > 0);//表示查询集合中Id大于0的数据
new LinqShow().Show();
}
{
public class LinqShow
{
#region Data Init
private List<Student> GetStudentList()
{
#region 初始化数据
List<Student> studentList = new List<Student>()
{
new Student()
{
Id=1,
Name="赵亮",
ClassId=2,
Age=35
},
new Student()
{
Id=1,
Name="再努力一点",
ClassId=2,
Age=23
},
new Student()
{
Id=1,
Name="王炸",
ClassId=2,
Age=27
},
new Student()
{
Id=1,
Name="疯子科学家",
ClassId=2,
Age=26
},
new Student()
{
Id=1,
Name="灭",
ClassId=2,
Age=25
},
new Student()
{
Id=1,
Name="黑骑士",
ClassId=2,
Age=24
},
new Student()
{
Id=1,
Name="故乡的风",
ClassId=2,
Age=21
},
new Student()
{
Id=1,
Name="晴天",
ClassId=2,
Age=22
},
new Student()
{
Id=1,
Name="旭光",
ClassId=2,
Age=34
},
new Student()
{
Id=1,
Name="oldkwok",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="乐儿",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="暴风轻语",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="一个人的孤单",
ClassId=2,
Age=28
},
new Student()
{
Id=1,
Name="小张",
ClassId=2,
Age=30
},
new Student()
{
Id=3,
Name="阿亮",
ClassId=3,
Age=30
},
new Student()
{
Id=4,
Name="37度",
ClassId=4,
Age=30
}
,
new Student()
{
Id=4,
Name="关耳",
ClassId=4,
Age=30
}
,
new Student()
{
Id=4,
Name="耳机侠",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Wheat",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Heaven",
ClassId=4,
Age=22
},
new Student()
{
Id=4,
Name="等待你的微笑",
ClassId=4,
Age=23
},
new Student()
{
Id=4,
Name="畅",
ClassId=4,
Age=25
},
new Student()
{
Id=4,
Name="混无痕",
ClassId=4,
Age=26
},
new Student()
{
Id=4,
Name="37度",
ClassId=4,
Age=28
},
new Student()
{
Id=4,
Name="新的世界",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Rui",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="帆",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="肩膀",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="孤独的根号三",
ClassId=4,
Age=30
}
};
#endregion
return studentList;
}
#endregion
public void Show()
{
List<Student> studentList = this.GetStudentList();
#region Linq 扩展方法&表达式
{
var list = studentList.Where<Student>(s => s.Age < 30); //list里面必然是符合要求的数据;
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.Name, item.Age);
}
}
{
Console.WriteLine("********************");
var list = from s in studentList
where s.Age < 30
select s; //list里面必然是符合要求的数据;
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.Name, item.Age);
}
}
#endregion
#region linq to object Show
{
Console.WriteLine("********************");
var list = studentList.Where<Student>(s => s.Age < 30)
.Select(s => new //投影:可以做一些自由组装+ new 一个匿名类,也可以new 具体类;
{
IdName = s.Id + s.Name,
ClassName = s.ClassId == 2 ? "高级班" : "其他班"
});
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.ClassName, item.IdName);
}
}
{
Console.WriteLine("********************");
var list = from s in studentList
where s.Age < 30
select new
{
IdName = s.Id + s.Name,
ClassName = s.ClassId == 2 ? "高级班" : "其他班"
};
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.ClassName, item.IdName);
}
}
{
Console.WriteLine("********************");
var list = studentList.Where<Student>(s => s.Age < 30)//条件过滤
.Select(s => new//投影
{
Id = s.Id,
ClassId = s.ClassId,
IdName = s.Id + s.Name,
ClassName = s.ClassId == 2 ? "高级班" : "其他班"
})
.OrderBy(s => s.Id)//排序 升序
.ThenBy(s => s.ClassName) //多重排序,可以多个字段排序都生效
.OrderByDescending(s => s.ClassId)//倒排
.Skip(2)//跳过几条 //必须要先排序
.Take(3)//获取几条 //必须要先排序
;
foreach (var item in list)
{
Console.WriteLine($"Name={item.ClassName} Age={item.IdName}");
}
}
{//group by·
Console.WriteLine("********************");
var list = from s in studentList
where s.Age < 30
group s by s.ClassId into sg
select new
{
key = sg.Key,
maxAge = sg.Max(t => t.Age)
};
foreach (var item in list)
{
Console.WriteLine($"key={item.key} maxAge={item.maxAge}");
}
//group by new {s.ClassId,s.Age}
//group by new {A=s.ClassId>1}
}
{
Console.WriteLine("********************");
var list = studentList.GroupBy(s => s.ClassId).Select(sg => new
{
key = sg.Key,
maxAge = sg.Max(t => t.Age)
});
foreach (var item in list)
{
Console.WriteLine($"key={item.key} maxAge={item.maxAge}");
}
}
{
var list = studentList.GroupBy(s => s.ClassId);
foreach (var date in list) ///实现了IEnumerable
{
Console.WriteLine(date.Key);
foreach (var item in date)
{
Console.WriteLine(item.Age);
}
}
}
List<Class> classList = new List<Class>()
{
new Class()
{
Id=1,
ClassName="架构班"
},
new Class()
{
Id=2,
ClassName="高级班"
},
new Class()
{
Id=3,
ClassName="全栈班"
},
};
{
//Join
var list = from s in studentList
join c in classList on s.ClassId equals c.Id //只能使用equals 不能使==
select new
{
Name = s.Name,
CalssName = c.ClassName
};
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
}
{
var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
{
Name = s.Name,
CalssName = c.ClassName
});
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
}
{//左连接
var list = from s in studentList
join c in classList on s.ClassId equals c.Id
into scList
from sc in scList.DefaultIfEmpty()//
select new
{
Name = s.Name,
CalssName = sc == null ? "无班级" : sc.ClassName//c变sc,为空则用
};
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
Console.WriteLine(list.Count());
}
{
var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
{
Name = s.Name,
CalssName = c.ClassName
}).DefaultIfEmpty();//为空就没有了
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
Console.WriteLine(list.Count());
}
{
//左连接和右链接 就是链接对象交换一下即可;
}
#endregion
}
}
}
Linq原理
{
public class LinqPrinciple
{
#region Data Init
private List<Student> GetStudentList()
{
#region 初始化数据
List<Student> studentList = new List<Student>()
{
new Student()
{
Id=1,
Name="赵亮",
ClassId=2,
Age=35
},
new Student()
{
Id=1,
Name="再努力一点",
ClassId=2,
Age=23
},
new Student()
{
Id=1,
Name="王炸",
ClassId=2,
Age=27
},
new Student()
{
Id=1,
Name="疯子科学家",
ClassId=2,
Age=26
},
new Student()
{
Id=1,
Name="灭",
ClassId=2,
Age=25
},
new Student()
{
Id=1,
Name="黑骑士",
ClassId=2,
Age=24
},
new Student()
{
Id=1,
Name="故乡的风",
ClassId=2,
Age=21
},
new Student()
{
Id=1,
Name="晴天",
ClassId=2,
Age=22
},
new Student()
{
Id=1,
Name="旭光",
ClassId=2,
Age=34
},
new Student()
{
Id=1,
Name="oldkwok",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="乐儿",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="暴风轻语",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="一个人的孤单",
ClassId=2,
Age=28
},
new Student()
{
Id=1,
Name="小张",
ClassId=2,
Age=30
},
new Student()
{
Id=3,
Name="阿亮",
ClassId=3,
Age=30
},
new Student()
{
Id=4,
Name="37度",
ClassId=4,
Age=30
}
,
new Student()
{
Id=4,
Name="关耳",
ClassId=4,
Age=30
}
,
new Student()
{
Id=4,
Name="耳机侠",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Wheat",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Heaven",
ClassId=4,
Age=22
},
new Student()
{
Id=4,
Name="等待你的微笑",
ClassId=4,
Age=23
},
new Student()
{
Id=4,
Name="畅",
ClassId=4,
Age=25
},
new Student()
{
Id=4,
Name="混无痕",
ClassId=4,
Age=26
},
new Student()
{
Id=4,
Name="37度",
ClassId=4,
Age=28
},
new Student()
{
Id=4,
Name="新的世界",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Rui",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="帆",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="肩膀",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="孤独的根号三",
ClassId=4,
Age=30
}
};
#endregion
return studentList;
}
#endregion
public void Show()
{
{
List<Student> students = GetStudentList();
students.Where(s => s.Age < 30);
}
//1.存在一个集合,如果想过滤其中的数据;a.定义一个新集合, b.把之前的集合循环, c 判断 条件,把符合条件的对象 添加到这个新集合中;
//问题:1.三个条件的筛选:有很多的重复代码---封装
// 2.条件不一样:都需要来这么一波判断+循环
//2.开始改变:把循环这些动作转移到方法中,多发方法还是有很多重复代码:
//特点:重复的代码在每个方法中都有---固定的业务逻辑;
// 唯一不同的就是条件; 条件是可变的;
//可以把不变的业务逻辑保留,把可变的,不固定的业务逻辑转移出去,让外面给我指定---怎么转移? 把一个行为转移出去---就是把一个行为从外面给传递过来? 就可以用委托包装一个方法传递过来;
//3.以下CustomWhere就是Linq的演变过程
//4.思路:通过方法封装+不变的逻辑封装在方法中,可变的逻辑,通过委托传递+ 扩展方法----Linq语句
//5.我们这里是查询的是Student,如果要查询其他的类型呢?过滤Teacher...,就需要一个方法满足不同类型的需求;---泛型方法嘛
//6.Linq中的Where 跟我们这个是一样的吗?-Linq的底层都是通过迭代器来实现就是支持循环;
//技术手段叫来说:是通过扩展方法来完成的;
//7.在扩展IEnumable的时候,可以使用yield 关键字,yield关键字必须和IEnumable 成套使用:---状态机的实现,yield关键做到了按需获取,判断的时候,只要是符合条件的,就返回了,如果不符合就继续往后判断;
//8.以上所说其实是Linq to Object:通过方法封装+不变的逻辑封装在方法中,可变的逻辑,通过委托传递+ 扩展方法,IEnumerable 通常认为他是一个内存数据:还有IQueryable
//Linq to Sql: 把不变的逻辑封装在内,把可变的Sql语句通过委托来进行传递:
//Linq to xml: 把不变的处理xml逻辑封装在内,把可变的处理Xml的路基通过委托来进行传递:
//Linq to Redis:
//Linq to Cache;
//...;.......
//Linq to EveryThing
//9:Linq是什么? Linq从技术上来说,确实是通过扩展方法来完成的, 从程序的设计上来说,就是把不变的业务逻辑转移;把固定的业务逻辑封装;整合起来---Linq; 代码的封装思想,封装套路;
//IQueryable<Student> students1 = null;
List<Student> studentList = this.GetStudentList();
//常规情况下数据过滤
//1.要求查询Student中年龄小于30的;
{
List<Student> list = new List<Student>();
foreach (var item in studentList)
{
if (item.Age < 30)
{
list.Add(item);
}
}
{
//List<Student> student = MethodExtension.RichardWhere(studentList);
////Func<Student, bool> func = new Func<Student, bool>(s =>
////{
//// return s.Age < 30;
////});
//Func<Student, bool> func = s => s.Age < 30;
//List<Student> student1 = MethodExtension.CustomWhere(studentList, func);
}
{
//List<Student> student2 = MethodExtension.CustomWhere(studentList, s => s.Age < 30);
//List<Student> student3 = studentList.CustomWhere(s => s.Age < 30);
//List<Student> student4 = studentList.Where(s => s.Age < 30).ToList();
//IEnumerable<Student> student5 = studentList.CustomWhereIEnumerable(s => s.Age < 30);
}
//测试yield 关键字的效果
{
Console.WriteLine("************************this is CustomWhere*************************");
List<Student> student2 = MethodExtension.CustomWhere(studentList, s => s.Age < 30);
foreach (var item in student2)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("************************this is CustomWhereIEnumerable*************************");
Console.WriteLine("************************使用yiled关键字以后*************************");
IEnumerable<Student> studentenumerable = MethodExtension.CustomWhereIEnumerable(studentList, s => s.Age < 30);
foreach (var item in studentenumerable)
{
Console.WriteLine(item.Name);
}
}
}
//2.要求Student名称长度大于2
{
//Name长度大于2的
var list = new List<Student>();
foreach (var item in studentList)
{
if (item.Name.Length > 2)
{
list.Add(item);
}
}
List<Student> student = MethodExtension.RichardWhere1(studentList);
List<Student> student3 = studentList.CustomWhere(s => s.Name.Length > 2);
IEnumerable<Student> student4 = studentList.CustomWhereIEnumerable(s => s.Name.Length > 2);
}
//3. N个条件叠加
{
var list = new List<Student>();
foreach (var item in studentList)
{
if (item.Id > 1
&& item.Name != null
&& item.ClassId == 1
&& item.Age > 20)
{
list.Add(item);
}
}
List<Student> student = MethodExtension.RichardWhere2(studentList);
List<Student> student3 = studentList.CustomWhere(item => item.Id > 1
&& item.Name != null
&& item.ClassId == 1
&& item.Age > 20);
IEnumerable<Student> student4 = studentList.CustomWhereIEnumerable(item => item.Id > 1
&& item.Name != null
&& item.ClassId == 1
&& item.Age > 20);
}
}
}
}
常见Linq语句
{
public class LinqShow
{
#region Data Init
private List<Student> GetStudentList()
{
#region 初始化数据
List<Student> studentList = new List<Student>()
{
new Student()
{
Id=1,
Name="赵亮",
ClassId=2,
Age=35
},
new Student()
{
Id=1,
Name="再努力一点",
ClassId=2,
Age=23
},
new Student()
{
Id=1,
Name="王炸",
ClassId=2,
Age=27
},
new Student()
{
Id=1,
Name="疯子科学家",
ClassId=2,
Age=26
},
new Student()
{
Id=1,
Name="灭",
ClassId=2,
Age=25
},
new Student()
{
Id=1,
Name="黑骑士",
ClassId=2,
Age=24
},
new Student()
{
Id=1,
Name="故乡的风",
ClassId=2,
Age=21
},
new Student()
{
Id=1,
Name="晴天",
ClassId=2,
Age=22
},
new Student()
{
Id=1,
Name="旭光",
ClassId=2,
Age=34
},
new Student()
{
Id=1,
Name="oldkwok",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="乐儿",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="暴风轻语",
ClassId=2,
Age=30
},
new Student()
{
Id=1,
Name="一个人的孤单",
ClassId=2,
Age=28
},
new Student()
{
Id=1,
Name="小张",
ClassId=2,
Age=30
},
new Student()
{
Id=3,
Name="阿亮",
ClassId=3,
Age=30
},
new Student()
{
Id=4,
Name="37度",
ClassId=4,
Age=30
}
,
new Student()
{
Id=4,
Name="关耳",
ClassId=4,
Age=30
}
,
new Student()
{
Id=4,
Name="耳机侠",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Wheat",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Heaven",
ClassId=4,
Age=22
},
new Student()
{
Id=4,
Name="等待你的微笑",
ClassId=4,
Age=23
},
new Student()
{
Id=4,
Name="畅",
ClassId=4,
Age=25
},
new Student()
{
Id=4,
Name="混无痕",
ClassId=4,
Age=26
},
new Student()
{
Id=4,
Name="37度",
ClassId=4,
Age=28
},
new Student()
{
Id=4,
Name="新的世界",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="Rui",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="帆",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="肩膀",
ClassId=4,
Age=30
},
new Student()
{
Id=4,
Name="孤独的根号三",
ClassId=4,
Age=30
}
};
#endregion
return studentList;
}
#endregion
public void Show()
{
List<Student> studentList = this.GetStudentList();
#region Linq 扩展方法&表达式
{
var list = studentList.Where<Student>(s => s.Age < 30); //list里面必然是符合要求的数据;
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.Name, item.Age);
}
}
{
Console.WriteLine("********************");
var list = from s in studentList
where s.Age < 30
select s; //list里面必然是符合要求的数据;
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.Name, item.Age);
}
}
#endregion
#region linq to object Show
{
Console.WriteLine("********************");
var list = studentList.Where<Student>(s => s.Age < 30)
.Select(s => new //投影:可以做一些自由组装+ new 一个匿名类,也可以new 具体类;
{
IdName = s.Id + s.Name,
ClassName = s.ClassId == 2 ? "高级班" : "其他班"
});
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.ClassName, item.IdName);
}
}
{
Console.WriteLine("********************");
var list = from s in studentList
where s.Age < 30
select new
{
IdName = s.Id + s.Name,
ClassName = s.ClassId == 2 ? "高级班" : "其他班"
};
foreach (var item in list)
{
Console.WriteLine("Name={0} Age={1}", item.ClassName, item.IdName);
}
}
{
Console.WriteLine("********************");
var list = studentList.Where<Student>(s => s.Age < 30)//条件过滤
.Select(s => new//投影
{
Id = s.Id,
ClassId = s.ClassId,
IdName = s.Id + s.Name,
ClassName = s.ClassId == 2 ? "高级班" : "其他班"
})
.OrderBy(s => s.Id)//排序 升序
.ThenBy(s => s.ClassName) //多重排序,可以多个字段排序都生效
.OrderByDescending(s => s.ClassId)//倒排
.Skip(2)//跳过几条 //必须要先排序
.Take(3)//获取几条 //必须要先排序
;
foreach (var item in list)
{
Console.WriteLine($"Name={item.ClassName} Age={item.IdName}");
}
}
{//group by·
Console.WriteLine("********************");
var list = from s in studentList
where s.Age < 30
group s by s.ClassId into sg
select new
{
key = sg.Key,
maxAge = sg.Max(t => t.Age)
};
foreach (var item in list)
{
Console.WriteLine($"key={item.key} maxAge={item.maxAge}");
}
//group by new {s.ClassId,s.Age}
//group by new {A=s.ClassId>1}
}
{
Console.WriteLine("********************");
var list = studentList.GroupBy(s => s.ClassId).Select(sg => new
{
key = sg.Key,
maxAge = sg.Max(t => t.Age)
});
foreach (var item in list)
{
Console.WriteLine($"key={item.key} maxAge={item.maxAge}");
}
}
{
var list = studentList.GroupBy(s => s.ClassId);
foreach (var date in list) ///实现了IEnumerable
{
Console.WriteLine(date.Key);
foreach (var item in date)
{
Console.WriteLine(item.Age);
}
}
}
List<Class> classList = new List<Class>()
{
new Class()
{
Id=1,
ClassName="架构班"
},
new Class()
{
Id=2,
ClassName="高级班"
},
new Class()
{
Id=3,
ClassName="全栈班"
},
};
{
//Join
var list = from s in studentList
join c in classList on s.ClassId equals c.Id //只能使用equals 不能使==
select new
{
Name = s.Name,
CalssName = c.ClassName
};
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
}
{
var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
{
Name = s.Name,
CalssName = c.ClassName
});
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
}
{//左连接
var list = from s in studentList
join c in classList on s.ClassId equals c.Id
into scList
from sc in scList.DefaultIfEmpty()//
select new
{
Name = s.Name,
CalssName = sc == null ? "无班级" : sc.ClassName//c变sc,为空则用
};
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
Console.WriteLine(list.Count());
}
{
var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
{
Name = s.Name,
CalssName = c.ClassName
}).DefaultIfEmpty();//为空就没有了
foreach (var item in list)
{
Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
}
Console.WriteLine(list.Count());
}
{
//左连接和右链接 就是链接对象交换一下即可;
}
#endregion
}
}
}