Core的学习过程中的笔记留痕
参考自杨中科老师的《ASP.NET Core技术内幕与项目实战——基于DDD与前后端分离》
样例数据
var superMan = new Man() { Name = "超人", Age = 33, Address = "美国" };
var batMan = new Man() { Name = "蝙蝠侠", Age = 40, Address = "美国" };
var spiderMan = new Man() { Name = "蜘蛛侠", Age = 17, Address = "美国纽约" };
List<Man> manList = new List<Man>();
manList.Add(superMan);
manList.Add(batMan);
manList.Add(spiderMan);
static string ToWrite(Man man)
{
return "姓名:" + man.Name + " 年龄:" + man.Age + " 地址:" + man.Address;
}
排序方法
OrderBy与OrderByDescending方法
var manAsc = manList.OrderBy(x => x.Age);
foreach (var man in manAsc)
{
Console.WriteLine("OrderBy方法"+ToWrite(man));
}
var manDesc = manList.OrderByDescending(x => x.Age);
foreach (var man in manDesc)
{
Console.WriteLine("OrderByDescending方法" + ToWrite(man));
}
限制结果集
Skip与Task方法
//跳过前两位
var manSkip = manList.Skip(2).First(); ;
Console.WriteLine("只获取第三位超级英雄:" + manSkip.Name);
//只获取第一位
var manTask = manList.Take(1).First(); ;
Console.WriteLine("只获取第一位超级英雄:"+ manTask.Name);
聚合函数
Max、Min、Average、Sum、Count
var max_Age = manList.Max(x => x.Age);
var min_Age = manList.Min(x => x.Age);
var avg_Age = manList.Average(x => x.Age);
Console.WriteLine($"他们中最大的{max_Age}岁,最小的{min_Age}岁,平均年龄{avg_Age}");
GroupBy方法
var manGroup = manList.GroupBy(x => x.Address);
foreach (var group in manGroup)
{
Console.WriteLine("GroupBy方法的Key:" + group.Key);
Console.WriteLine($"{group.Key}有{group.Count()}位超级英雄,最大的{group.Max(x=>x.Age)}岁了" );
}
var orderGroup = orderPlan.Where(x => x.UnrStk < 0)
.GroupBy(x => x.Material)
.Select(x => new ProductPlanGroup
{
Material = x.Key,
PlanQty = 0,
PlanAccount = x.Min(y=>y.UnrStk),
FirstDate = x.Min(y => y.ReqstDate),
ScheduleNum = x.Max(y => y.ScheduledNum),
FinishNum = x.Max(y => y.FinQty)
}).ToList();
Select方法
var manSelect = manList.Select(x=> x.Name);
Console.WriteLine(string.Join(", ", manSelect));
//使用双目运算符,改变集合结果
var manSelectIs = manList.Select(x => x.Age < 18 ? "少年" : "成年");
Console.WriteLine(string.Join(", ", manSelectIs));
注释:还可以建立新的类型,进行new后使用
综合使用的例子加ToArray与ToList方法
var ultraMan = new {Address = "光之国", CountMan = 6};
var manToList = manList.Where(x => x.Age < 35)
.GroupBy(x => x.Address)
.OrderBy(x => x.Key)
.Take(2)
.Select(x => new
{
Address = x.Key,
CountMan = x.Count()
}).ToList();
//这两个方法的区别
manToList.Add(ultraMan);
foreach (var item in manToList)
{
Console.WriteLine("ToList方法:" + item);
}
var manToArray = manList.Where(x => x.Age < 35)
.GroupBy(x => x.Address)
.OrderBy(x => x.Key)
.Take(2)
.Select(x => new
{
Address = x.Key,
CountMan = x.Count()
}).ToArray();
foreach (var item in manToArray)
{
Console.WriteLine("ToArray方法:"+item);
}
注释:
ToArray与ToList方法的区别:
1、返回类型不同:
ToArray返回的数组(T[])
ToList返回的列表(List<T>)
2、可变性:
数组的大小是固定的,不能动态调整
列表是可变的,可以动态调整大小
ToList()后可以添加(Add、Remove、Insert)等方法,改变数组大小