From 322ee18526dd73b61788420e3e17ac472a45fb49 Mon Sep 17 00:00:00 2001 From: bmchu070 <1549098850@qq.com> Date: Sun, 8 Dec 2024 21:38:37 +0800 Subject: [PATCH] 20241208 --- ...15\346\235\202\344\274\240\345\217\202.md" | 64 +++ .../20241127-\350\247\206\345\233\276.md" | 33 ++ ...6\345\210\240\346\224\271\346\237\2451.md" | 95 ++++ ...06\346\210\220\346\237\245\350\257\242.md" | 28 + ...6\345\210\240\346\224\271\346\237\2452.md" | 79 +++ .../20241130-\344\270\223\351\241\271.md" | 495 ++++++++++++++++++ .../20241207-Linq.md" | 391 ++++++++++++++ 7 files changed, 1185 insertions(+) create mode 100644 "\347\216\213\350\212\267\345\256\201/20241125-\345\244\215\346\235\202\344\274\240\345\217\202.md" create mode 100644 "\347\216\213\350\212\267\345\256\201/20241127-\350\247\206\345\233\276.md" create mode 100644 "\347\216\213\350\212\267\345\256\201/20241202-\345\242\236\345\210\240\346\224\271\346\237\2451.md" create mode 100644 "\347\216\213\350\212\267\345\256\201/20241204-Linq\351\233\206\346\210\220\346\237\245\350\257\242.md" create mode 100644 "\347\216\213\350\212\267\345\256\201/20241205-\345\242\236\345\210\240\346\224\271\346\237\2452.md" create mode 100644 "\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241130-\344\270\223\351\241\271.md" create mode 100644 "\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241207-Linq.md" diff --git "a/\347\216\213\350\212\267\345\256\201/20241125-\345\244\215\346\235\202\344\274\240\345\217\202.md" "b/\347\216\213\350\212\267\345\256\201/20241125-\345\244\215\346\235\202\344\274\240\345\217\202.md" new file mode 100644 index 0000000..c7983e6 --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/20241125-\345\244\215\346\235\202\344\274\240\345\217\202.md" @@ -0,0 +1,64 @@ +### 关于Action的返回值 + +1. 基础数据类型 `int,string,List<>等等` +2. IActionResult,返回响应的状态码 + - 视图 + - 重定向(RedirectToAction("index")--在同一个控制器下) + ``` + public IActionResult List() + { + return RedirectToAction("index"); + } + + public IActionResult Index() + { + return View(); + } + ``` +3. ActionResult,是前面2个结合体,意思为既可以返回基础数据类型,也可以返回响应状态 +4. 内容响应:JsonResult,ContentResult +5. POCO(比较老的类型对象) + +### 序列化 反序列化 +``` + 序列化 反序列化 + | | + 信息--->网络--->信息 + | | + 传输媒介 网络设备 +``` + +### 基础数据类型使用 +``` + public List Index() + { + var list=new List{ + 1,2,3,4,5 + }; + return list; + } +``` + +### ActionResult使用 +``` + public ActionResult Index() + { + var i=1==3; + //判断是否成立 + if(i){ + return View(); + }else{ + return true; + } + } +``` + +### 内容响应JsonResult使用 +``` + public dynamic Index(){ + var obj=new {Name="张三",Age=19};//动态类型 + return obj; + } +``` + + diff --git "a/\347\216\213\350\212\267\345\256\201/20241127-\350\247\206\345\233\276.md" "b/\347\216\213\350\212\267\345\256\201/20241127-\350\247\206\345\233\276.md" new file mode 100644 index 0000000..c64eb00 --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/20241127-\350\247\206\345\233\276.md" @@ -0,0 +1,33 @@ +## 视图 + +### Razor语法 +1. 专业说法:模版引擎 + - 大部分时候,都是通过View()函数,传入数据给视图,这样一来,在视图中就可以通过@Model这个来获取数据 + - 实际上,可以通过声明视图模型的类型,来获得自动提示或者自动感知 +2. 使用foreach循环输出集合List + ``` + @foreach(var item in Student) + { + @item.StudentName + } + ``` + + +### 在视图上显示数据 + +1. 在视图上定义简单数据,在视图上显示 + ``` + @{ + var ao="hzhf"; + } + @ao + ``` +2. 在视图定义对象数据,集合数据 +3. 在后端传回来的集合数据 +4. 在后端传回来的对象数据 + +### 定位点标记 +1. `***` +2. `***` + + diff --git "a/\347\216\213\350\212\267\345\256\201/20241202-\345\242\236\345\210\240\346\224\271\346\237\2451.md" "b/\347\216\213\350\212\267\345\256\201/20241202-\345\242\236\345\210\240\346\224\271\346\237\2451.md" new file mode 100644 index 0000000..30c9ebf --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/20241202-\345\242\236\345\210\240\346\224\271\346\237\2451.md" @@ -0,0 +1,95 @@ +## 增删改查 + +1. 创建mvc文件 +``` +dotnet new mvc -o 'Blog' +``` + +2. 控制器创建BlogsController.cs +```c# + using Microsoft.AspNetCore.Mvc; + using Blog.Models; + + namespace Blog.Controllers; + + public IActionResult Index() + { + return View(Db.Blogs); + } + //显示添加页面 + public IActionResult Add() + { + return View(); + } + //显示删除页面 + public IActionResult Delete() + { + return View(); + } + //显示编辑页面 + public IActionResult Create() + { + return View(); + } +``` + +2. 创View与控制器同名的Blogs +3. Blogs中创视图Index + - 可以在里面使用`xx`来跳转页 + - 声明`@model List`--可以提示 +4. Index中搭建CURD 的结构 +5. 优化页面 css + + 引用css link `href="~/css/base.css"` +6. Model创Blogs.cs;让视图活起来(代表数据库表模型) + + 在里面定义字段 + ```c# + public class Blogs{ + public int Id{get;set;} + public string Title{get;set;}=null!; + public string Content{get;set;}=null!; + public string Author{get;set;}=null!; + } + ``` +7. 创数据库表Db.cs;模拟数据库所以用静态 + ```c# + public static class Db{ + Public static List Blogs{get;set;} + //构造函数 + static Db(){ + //桶 + Blog = []//Blog = new List(); + for (var i=0;i<10;i++>){ + 化//数组话 + var tmp = new Blogs{ + //应为从0开始所以要加1 + Id=i+1, + Title = $"文字{i}", + Content = $"文字{i}", + Author = $"文字{i}" + }; + //将tmp添加到List中 + Blogs.Add(tmp); + + } + } + } + ``` +8. 在控制器return View(Db.Blogs); +9. 视图中声明`@model List;` +10. 将页面变为动态 +```c# + + @foreach(var item in @Model) + { + + @item.Id + @item.Title + @item.Content + @item.Author + + 编辑 + 删除 + + + } +``` \ No newline at end of file diff --git "a/\347\216\213\350\212\267\345\256\201/20241204-Linq\351\233\206\346\210\220\346\237\245\350\257\242.md" "b/\347\216\213\350\212\267\345\256\201/20241204-Linq\351\233\206\346\210\220\346\237\245\350\257\242.md" new file mode 100644 index 0000000..a70aebf --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/20241204-Linq\351\233\206\346\210\220\346\237\245\350\257\242.md" @@ -0,0 +1,28 @@ +## Linq集成查询(关联Lambda) +1. First FirstOrDefaualt 找第一个符合条件的元素 + - First(x=>x.Id==id) 返回第一个Id等于id的元素,如果都没有符合的,报错 + - FirstOrDefault(x=>x.Id==id) 返回第一个Id等于id的元素,如果都没有符合的,返回Null +2. Single SingleOrDefault + - Single() 返回第一个元素,如果没有,报错 + - SingleOrDefault() 返回第一个元素,如果没有,返回Null +3. Where + - Where(x=>x.Score>=80 && x.Sex==1) 查找所有成绩大于等于80,并且性别为1的所有元素 +4. Select + - Select(x=>new {x.Id,x.Score}) 以新的{x.Id,x.Score}对象的形式,返回新的集合 +``` +from 查找的元素 in 数组/属性…… +where 条件 +orderby 排序条件(orderby升序,orderby 条件 descending降序) +select 结果; +``` + +## 表单标记 +```cshtml +
+``` + +生成以下 HTML: +```html +
+``` + diff --git "a/\347\216\213\350\212\267\345\256\201/20241205-\345\242\236\345\210\240\346\224\271\346\237\2452.md" "b/\347\216\213\350\212\267\345\256\201/20241205-\345\242\236\345\210\240\346\224\271\346\237\2452.md" new file mode 100644 index 0000000..a457f5b --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/20241205-\345\242\236\345\210\240\346\224\271\346\237\2452.md" @@ -0,0 +1,79 @@ +# 步骤 + +## 删除步骤 +1. 需要再Index.cshtml页面中`删除`获取Id值 +2. Delete.cshtml中的样式 + ```c# + @model Blog.Models.Blogs; +

你真的要删除吗?

+ + + + + + + + + + + + + + + + + +
标题@Model.Title
内容@Model.Content
作者@Model.Author
删除回到主页
+ ``` +3. 展示删除页面 + ```c# + public IActionResult Delete(int id) + { + //根据id找到对应的blog + var blog=Db.Blogs.FirstOrDefault(X=>X.Id==id); + return View(blog); + } + ``` +4. 确认删除页面 + ```c# + public IActionResult DeleteConfirm(int id) + { + //根据id找到对应的blog + var blog=Db.Blogs.FirstOrDefault(X=>X.Id==id); + //如果blog不为空,查找出来就删除 + if(blog!=null) + { + Db.Blogs.Remove(blog); + //删除完返回列表页 + return RedirectToAction("Index"); + } + //如果找不到就返回找不到提示 + return NotFound(); + } + ``` + + +## 查询步骤 +1. Index.cshtml的查询样式 + ```c# +
+ + +
+ ``` +2. 查询页面 + ```c# + public IActionResult Index(string keyword) + { + //判读keyword是否为空,不为空则删除空格 + keyword=string.IsNullOrEmpty(keyword)?"":keyword.Trim(); + //如果为空返回主页 + if(string.IsNullOrEmpty(keyword)) + { + return View(Db.Blogs); + } + //如果不为空,则查询 + var list=Db.Blogs.Where(x=>x.Title.Contains(keyword)||x.Content.Contains(keyword)||x.Author.Contains(keyword)).ToList(); + return View(list); + } + ``` \ No newline at end of file diff --git "a/\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241130-\344\270\223\351\241\271.md" "b/\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241130-\344\270\223\351\241\271.md" new file mode 100644 index 0000000..5619b91 --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241130-\344\270\223\351\241\271.md" @@ -0,0 +1,495 @@ +## 专项练习-控制器传参 +1. 简单参数传递 在一个叫Blog控制器中,定义一个叫Index的Action,并且传递一个int类型的值,id为变量名 +``` +public class BlogsController : Controller +{ + public ActionResult Index(int id) + { + return View(); + } +} +``` +2. 简单参数传递 在一个叫Blog控制器中,定义一个叫Index_2的Action,并且传递一个string类型的值,id为变量名 +``` +public class BlogsController : Controller +{ + public ActionResult Index_2(string id) + { + return View(); + } +} +``` +3. 简单参数传递 在一个叫Blog控制器中,定义一个叫Index_3的Action,并且传递一个string类型的值,name为变量名 +``` +public class BlogsController : Controller +{ + public ActionResult Index_3(string name) + { + return View(); + } +} +``` +4. 复杂参数传递 在一个叫Blog的控制器中,定义一个名为Create的Action,并且传递一个BlogCreateDto类型的值,blogCreateDto为变量名,BlogCreateDto类型具有Title、Author、Content自动属性 + 1. 定义BlogsCreateDto类: + ``` + public class BlogCreateDto + { + public string Title { get; set; } + public string Author { get; set; } + public string Content { get; set; } + } + ``` + 2. 你可以在 Blog 控制器中定义 Create Action 方法: + ``` + public class BlogController : Controller + { + [HttpPost] + public ActionResult Create(BlogCreateDto blogCreateDto) + { + if (ModelState.IsValid) + { + return RedirectToAction("Success"); + } + return View(blogCreateDto); + } + } + ``` +5. 复杂参数传递 在一个叫Blog的控制器中,定义一个名为Create_1的Action,并且传递一个Products类型的值,productCreateDto为变量名, PS Products类型具有Name、 Price、Stock自动属性 + 1. 定义Products类 + ``` + public class Products + { + public string Name { get; set; } + public decimal Price { get; set; } + public int Stock { get; set; } + } + ``` + 2. 在 Blog 控制器中定义 Create_1 Action 方法: + ``` + public class BlogController : Controller + { + [HttpPost] + public ActionResult Create_1(Products productCreateDto) + { + if (ModelState.IsValid) + { + return RedirectToAction("Success"); + } + return View(productCreateDto); + } + } + ``` + +6. 复杂参数传递 在一个叫Blog的控制器中,定义一个名为Create_2的Action,并且传递一个Students类型的值,studentCreateDto为变量名,PS Students类型具有StudentName、Sex、Age自动属性 + 1. 定义Students类 + ``` + public class Students + { + public string StudentName { get; set; } + public string Sex { get; set; } + public int Age { get; set; } + } + ``` + + 2. 在 Blog 控制器中定义 Create_2 Action 方法: + ``` + public class BlogController : Controller + { + [HttpPost] + public ActionResult Create_2(Students studentCreateDto) + { + if (ModelState.IsValid) + { + return RedirectToAction("Success"); + } + return View(studentCreateDto); + } + } + ``` +## 专项练习-基础能力 + +1. 生成一个随机整数,范围[0,100],注意是否包含 + + ```csharp + public IActionResult GetRandom1() + { + Random random = new Random(); + return Content(random.Next(0, 101).ToString()); + } + +2. 生成一个随机整数,范围(0,100],注意是否包含 + + ```csharp + public IActionResult GetRandom2() + { + Random random = new Random(); + return Content(random.Next(1, 101).ToString()); + } + ``` + +3. 生成10个随机整数,范围[5, 80], 注意是否包含 + + ```csharp + public IActionResult GetRandom3() + { + Random random = new Random(); + string text = ""; + + for (int i = 0; i < 10; i++) + { + text = text + random.Next(5, 81); + if (i < 9) + { + text += " "; + } + } + return Content(text); + } + ``` + +4. 定义一个字符串,字符串中有100个中文字符,需要从中随机取1个字符串 + + ```csharp + public IActionResult GetRandom4() + { + string ChineseString = "这里说是要写一百个字但是我实在不知道要写点什么才好不知不觉就已经写了四分之一了很快啊就能写满了已经一半了什么时候下课啊好想放学啊谁懂床有多想我灵魂归宿任何时间任何地点超级困蛋魂归床畔已经准备好去睡觉了"; + Random random = new Random(); + int index = random.Next(ChineseString.Length); + return Content(ChineseString[index].ToString()); + } + ``` + +5. 定义一个字符串,字符串中有100个中文字符,需要从中随机取5-50个字符,组成新的字符 + + ```csharp + public IActionResult GetRandom5() + { + string ChineseString = "这里说是要写一百个字但是我实在不知道要写点什么才好不知不觉就已经写了四分之一了很快啊就能写满了已经一半了什么时候下课啊好想放学啊谁懂床有多想我灵魂归宿任何时间任何地点超级困蛋魂归床畔已经准备好去睡觉了"; + + Random random = new Random(); + + int RandomNumber = random.Next(5, 51); + string text = ""; + for (int i = 0; i < RandomNumber; i++) + { + int index = random.Next(ChineseString.Length); + text += ChineseString[index].ToString(); + if (i < RandomNumber - 1) + { + text += " "; + } + } + return Content(text); + } + ``` + +6. 定义2个字符串,第一个字符串中放百家姓,第二个字符串中放中文字符,要求从第一个字符串随机取得一个姓,再从第二个字符串中随机获得1到2个字符组成新字符串,和第一个字符串取得的姓组成一个姓名 + + ```csharp + public IActionResult GetRandom6() + { + string baijiaxing = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹孟高林何马陶冯程严唐"; + string chineseChars = "这里说是要写一百个字但是我实在不知道要写点什么才好不知不觉就已经写了四分之一了很快啊就能写满了已经一半了什么时候下课啊好想放学啊谁懂床有多想我灵魂归宿任何时间任何地点超级困蛋魂归床畔已经准备好去睡觉了"; + + Random random = new Random(); + + int LastNameRandom = random.Next(baijiaxing.Length); + string LastNameText = baijiaxing[LastNameRandom].ToString(); + + string FirstNameText = ""; + + // 1-2 + int FirstNameRandomNumber = random.Next(1, 3); + for (int i = 0; i < FirstNameRandomNumber; i++) + { + int FirstNameRandom2 = random.Next(chineseChars.Length); + string FirstNameChar = chineseChars[FirstNameRandom2].ToString(); + + FirstNameText += FirstNameChar; + } + return Content(LastNameText + FirstNameText); + } + ``` + +7. 利用以上方法,随机生成100个BlogCreateDto类型(有Title、Author、Content属性)的对象,其中的内容都是随机生成且长度不定,并将其渲染到视图 + + ```csharp + public IActionResult GetRandom7() + { + string baijiaxing = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹孟高林何马陶冯程严唐"; + string chineseChars = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘"; + + Random random = new Random(); + + // 定义一个列表用于存储100个随机生成的 BlogCreateDto + var blogList = new List(); + + // 生成100个 BlogCreateDto 对象 + for (int i = 0; i < 100; i++) + { + // 随机生成标题 Title + int titleLength = random.Next(5, 11); + string title = ""; + + for (int t = 0; t < titleLength; t++) + { + int index = random.Next(chineseChars.Length); + title += chineseChars[index]; + } + + // 随机生成作者 Author + + int LastNameRandom = random.Next(baijiaxing.Length); + string LastNameText = baijiaxing[LastNameRandom].ToString(); + + string FirstNameText = ""; + int FirstNameRandomNumber = random.Next(1, 3); + for (int j = 0; j < FirstNameRandomNumber; j++) + { + int FirstNameRandom2 = random.Next(chineseChars.Length); + string FirstNameChar = chineseChars[FirstNameRandom2].ToString(); + + FirstNameText += FirstNameChar; + } + string author = LastNameText + FirstNameText; + + // 随机生成内容 Content + int randomContentLength = random.Next(20, 50); + string content = ""; + for (int k = 0; k < randomContentLength; k++) + { + int contentIndex = random.Next(chineseChars.Length); + content += chineseChars[contentIndex].ToString(); + } + + BlogCreateDto blog = new BlogCreateDto + { + Title = title, + Author = author, + Content = content + }; + + blogList.Add(blog); + } + + return View(blogList); + } + ``` + ## 专项练习-控制器返回值 +1. 渲染简单数据到页面 ++ Model代码: + ``` + namespace Blog.Models; + + //第一步先定义字段 + + public class StudentsCreateDto{ + public string StudentName{get;set;}=null!; + public string Age{get;set;}=null!; + public string Height{get;set;}=null!; + + } + ``` ++ 控制器代码 + ``` + //控制器 + using Microsoft.AspNetCore.Mvc; + using Blog.Models; + + namespace Blog.Controllers; + + public class BlogsController : Controller { + public IActionResult List(){ + return RedirectToAction("index"); + } + //第二步再使用Model里面的字段 + public dynamic Index(){//序列化反序列化 + + var obj= new StudentsCreateDto{ + StudentName="CCC", + Age = "26", + Height ="176" + }; + return View(obj); + + } + } + ``` ++ 视图代码: + ``` + @{ + var str= "AAA"; + } + @str + +

@str

+ + ``` + +2. 渲染复杂数据到页面 + Model,控制器如上; + 视图如下: + ``` + @Model.StudentName + +

@Model.Age

+ ``` +3. 渲染集合数据到页面 ++ Model代码如上 ++ 控制器代码: + ``` + using Microsoft.AspNetCore.Mvc; + using Blog.Models; + + namespace Blog.Controllers; + + public class BlogsController : Controller { + public IActionResult List(){ + return RedirectToAction("index"); + } + + //第二步再使用Model里面的字段 + public dynamic Index(){//序列化反序列化 + var list=new List{ + new StudentsCreateDto { + StudentName="oppo", + Age = "18", + Height ="178" + }, + new StudentsCreateDto { + StudentName="vivo", + Age = "19", + Height ="178" + }, + new StudentsCreateDto { + StudentName="荣耀", + Age = "20", + Height ="155" + }, + }; + return View(list); + } + } + ``` ++ 效果: +3. 视图里调用: + ``` + @foreach(var item in @Model){ +

@item.StudentName

+ } + ``` + +## 专项练习-视图及其模板引擎 + +1.渲染(展示)简单数据类型到视图 + +- 在控制器中传递简单数据(如 `string`、`int` 等)到视图: + +```csharp +public IActionResult ShowMessage() +{ + string message = "欢迎来到 ASP.NET Core MVC!"; + return View(message); +} +``` + +在视图中显示数据: + +```html +@model string +

消息: @Model

+``` + + +2.渲染(展示)对象数据到视图 + +- 在控制器中传递对象数据(如自定义类)到视图: + +```csharp +public IActionResult ShowPerson() +{ + var person = new Person { Name = "Alice", Age = 30 }; + return View(person); +} +``` + +在视图中显示对象数据: + +```html + +@model Person +

姓名: @Model.Name

+

年龄: @Model.Age

+``` + +------ + +3.渲染(展示)集合数据到视图 + +- 在控制器中传递集合数据(如 `List<>`)到视图: + +```csharp +public IActionResult ShowItems() +{ + var items = new List { "苹果", "香蕉", "橙子" }; + return View(items); +} +``` + +在视图中显示集合数据: + +```html + +@model List +
    + @foreach (var item in Model) + { +
  • @item
  • + } +
+``` + +4.渲染(展示)包含集合数据的对象数据到视图 + +- 在控制器中传递包含集合的对象数据到视图: + +```csharp +public class Category +{ + public string Name { get; set; } + public List Products { get; set; } +} + +public IActionResult ShowCategory() +{ + var category = new Category + { + Name = "水果", + Products = new List { "苹果", "香蕉", "橙子" } + }; + return View(category); +} +``` + +在视图中渲染包含集合的对象数据: + +```html + +@model Category +

分类: @Model.Name

+
    + @foreach (var product in Model.Products) + { +
  • @product
  • + } +
+``` + +------ + +5.构建经典 CRUD 列表 + +```csharp + +``` + diff --git "a/\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241207-Linq.md" "b/\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241207-Linq.md" new file mode 100644 index 0000000..d9747f0 --- /dev/null +++ "b/\347\216\213\350\212\267\345\256\201/\344\275\234\344\270\232/20241207-Linq.md" @@ -0,0 +1,391 @@ +## 专项练习-Linq集成查询和Lambda表达式 + +### 基础练习 + +1. **查询特定元素** + 找出数组中等于5的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6 }; + + var query = numbers.Where(n => n == 5); + ``` + +2. **查询特定范围的元素** + 找出数组中在2到8之间的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6 }; + + var query1 = numbers.Where(n => n >= 2 && n <= 8); + ``` + +3. **查询并转换元素** + 将数组中的每个数字乘以2。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6 }; + + var query = numbers.Select(n => n * 2); + ``` + +4. **查询特定属性的对象** + 找出所有名字以"王"开头的学生。 + + ```csharp + List students = new List + { + new Student {Id=1, Name = "王有才", Age = 21 }, + new Student {Id=2, Name = "王中王", Age = 22 }, + new Student {Id=3, Name = "张语嫣", Age = 23 }, + new Student {Id=4, Name = "詹宇航", Age = 35 }, + new Student {Id=5, Name = "郑雨良", Age = 26 }, + }; + + var wangStu = students.Where(name => name.Name.StartsWith("王")); + foreach (var stu in wangStu) + { + Console.WriteLine(stu.Name); + } + ``` + +5. **查询并排序** + 找出所有年龄大于20岁的学生,并按年龄降序排列。 + + ```csharp + List students = new List + { + new Student {Id=1, Name = "王有才", Age = 21 }, + new Student {Id=2, Name = "罗婷", Age = 21 }, + new Student {Id=3, Name = "王中王", Age = 22 }, + new Student {Id=4, Name = "李子柒", Age = 22 }, + new Student {Id=5, Name = "张语嫣", Age = 23 }, + new Student {Id=6, Name = "詹宇航", Age = 35 }, + new Student {Id=7, Name = "郑雨良", Age = 26 }, + new Student {Id=8, Name = "欧文", Age = 26 }, + }; + var sortedStudents = students.Where(s => s.Age > 20).OrderByDescending(s => s.Age); + foreach (var stu in sortedStudents) + { + Console.WriteLine(stu.Name); + } + ``` + +6. **查询并去重** + 找出数组中所有不重复的数字。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var distinctResult = numbers.Distinct(); + foreach (var num in distinctResult) + { + Console.WriteLine(num); + } + ``` + +7. **查询第一个元素** + 找出数组中第一个大于3的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var first = numbers.FirstOrDefault(n => n > 3); + Console.WriteLine(first); + ``` + +8. **查询最后一个元素** + 找出数组中最后一个小于7的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var last = numbers.Where(n => n < 7).Last(); + Console.WriteLine(last); + ``` + +9. **查询元素是否存在** + 检查数组中是否存在大于10的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + bool i = numbers.Any(n => n > 10); + Console.WriteLine(i); + ``` + +10. **查询元素的计数** + 计算数组中大于5的元素数量。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + int num = numbers.Count(n => n > 5); + Console.WriteLine(num); + ``` + +11. **查询元素的总和** + 计算数组中所有元素的总和。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + int sum = numbers.Sum(); + Console.WriteLine($"总和: {sum}"); + ``` + +12. **查询元素的最大值** + 找出数组中的最大值。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + int max = numbers.Max(); + Console.WriteLine($"最大值: {max}"); + ``` + +13. **查询元素的最小值** + 找出数组中的最小值。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + int min = numbers.Min(); + Console.WriteLine($"最小值: {min}"); + ``` + +14. **查询元素的平均值** + 计算数组中所有元素的平均值。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + double average = numbers.Average(); + Console.WriteLine($"平均值: {average}"); + ``` + +15. **查询特定条件的元素** + 找出数组中能被3整除的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var divisibleBy3 = numbers.Where(n => n % 3 == 0); + foreach (var num in divisibleBy3) + { + Console.WriteLine(num); + } + ``` + +##### 中级练习 + +16. **查询并选择特定属性** + 找出所有学生的姓名和年龄。 + + ```csharp + List students = new List + { + new Student {Id=1, Name = "王有才", Age = 21 }, + new Student {Id=2, Name = "罗婷", Age = 21 }, + new Student {Id=3, Name = "王中王", Age = 22 }, + new Student {Id=4, Name = "李子柒", Age = 22 }, + new Student {Id=5, Name = "张语嫣", Age = 23 }, + new Student {Id=6, Name = "詹宇航", Age = 35 }, + new Student {Id=7, Name = "郑雨良", Age = 26 }, + new Student {Id=8, Name = "欧文", Age = 26 }, + }; + var result = students.Select(s => new { s.Name, s.Age }).ToList(); + foreach (var item in result) + { + Console.WriteLine($"Name: {item.Name}, Age: {item.Age}"); + } + ``` + +17. **查询并分组** + 按年龄分组学生,并计算每个年龄组的学生数量。 + + ```csharp + List students = new List + { + new Student {Id=1, Name = "王有才", Age = 21 }, + new Student {Id=2, Name = "罗婷", Age = 21 }, + new Student {Id=3, Name = "王中王", Age = 22 }, + new Student {Id=4, Name = "李子柒", Age = 22 }, + new Student {Id=5, Name = "张语嫣", Age = 23 }, + new Student {Id=6, Name = "詹宇航", Age = 35 }, + new Student {Id=7, Name = "郑雨良", Age = 26 }, + new Student {Id=8, Name = "欧文", Age = 26 }, + }; + var groupedByAge = students + .GroupBy(s => s.Age) + .Select(g => new { Age = g.Key, Count = g.Count() }) + .ToList(); + foreach (var item in groupedByAge) + { + Console.WriteLine($"Age: {item.Age}, Count: {item.Count}"); + } + ``` + +18. **查询并联结** + 联结学生和课程表,找出每个学生的所有课程。 + + ```csharp + List students = new List + { + new Student {Id=1, Name = "王有才", Age = 21 }, + new Student {Id=2, Name = "罗婷", Age = 21 }, + new Student {Id=3, Name = "王中王", Age = 22 }, + new Student {Id=4, Name = "李子柒", Age = 22 }, + new Student {Id=5, Name = "张语嫣", Age = 23 }, + new Student {Id=6, Name = "詹宇航", Age = 35 }, + new Student {Id=7, Name = "郑雨良", Age = 26 }, + new Student {Id=8, Name = "欧文", Age = 26 }, + }; + List courses=new List + { + new Course{StudentId=1,CourseName="英语"}, + new Course{StudentId=1,CourseName="数学"}, + new Course{StudentId=2,CourseName="语文"}, + new Course{StudentId=3,CourseName="物理"}, + new Course{StudentId=4,CourseName="化学"}, + new Course{StudentId=4,CourseName="生物"}, + new Course{StudentId=4,CourseName="语文"}, + }; + var query = + from student in students + join course in courses on student.Id equals course.StudentId + select new { student.Name, course.CourseName }; + + foreach (var item in query) + { + Console.WriteLine($"Name: {item.Name}, Course: {item.CourseName}"); + } + ``` + +19. **查询并反转** + 反转数组中的元素顺序。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var reversed = numbers.Reverse().ToArray(); + foreach (var num in reversed) + { + Console.WriteLine(num); + } + ``` + +20. **查询并填充** + 找出数组中第一个大于2的元素,并用它填充后面的所有位置。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + int firstGreaterThanTwo = numbers.FirstOrDefault(n => n > 2); + for ( + int i = numbers.IndexOf(numbers.FirstOrDefault(n => n > 2)); + i < numbers.Length; + i++ + ) + { + numbers[i] = firstGreaterThanTwo; + } + foreach (var num in numbers) + { + Console.WriteLine(num); + } + ``` + +21. **查询并排除** + 从数组中排除所有小于5的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var filtered = numbers.Where(n => n > 5).ToArray(); + foreach (var num in filtered) + { + Console.WriteLine(num); + } + ``` + +22. **查询并填充默认值** + 如果数组中存在null值,用默认值0替换。 + + ```csharp + int?[] nullableNumbers = { 1, null, 3, null, 5 }; + + var filled = nullableNumbers.Select(n => n ?? 0).ToArray(); + foreach (var num in filled) + { + Console.WriteLine(num); + } + ``` + +23. **查询并转换类型** + 将字符串数组转换为整数数组。 + + ```csharp + string[] stringNumbers = { "1", "2", "3", "4" }; + var intNumbers = stringNumbers.Select(int.Parse).ToArray(); + foreach (var num in intNumbers) + { + Console.WriteLine(num); + } + ``` + + +24. **查询并使用OfType过滤** + 从对象数组中过滤出字符串类型的元素。 + + ```csharp + object[] objects = { "String", 123, "Another String", 456 }; + var result = objects.OfType().ToList(); + foreach (var str in result) + { + Console.WriteLine(str); + } + ``` + +##### 高级练习 + +25. **查询并使用Zip合并** + 合并两个数组,并创建一个包含元素对的新数组。 + + ```csharp + int[] numbers1 = { 1, 2, 3 }; + int[] numbers2 = { 4, 5, 6 }; + var zipped = numbers1 + .Zip(numbers2, (n1, n2) => new { Number1 = n1, Number2 = n2 }) + .ToArray(); + Console.WriteLine("Zipped:"); + foreach (var pair in zipped) + { + Console.WriteLine($"({pair.Number1}, {pair.Number2})"); + } + ``` + +26. **查询并使用Range生成** + 生成一个包含1到10的整数数组。 + + ```csharp + var range = Enumerable.Range(1, 10).ToArray(); + Console.WriteLine("\nRange:"); + Console.WriteLine(string.Join(", ", range)); + ``` + +27. **查询并使用Repeat重复** + 重复一个元素多次,创建一个新数组。 + + ```csharp + var repeated = Enumerable.Repeat(7, 5).ToArray(); + Console.WriteLine("\nRepeated:"); + Console.WriteLine(string.Join(", ", repeated)); + ``` + +28. **查询并使用Take限制数量** + 从数组中取出前5个元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var taken = numbers.Take(5).ToArray(); + Console.WriteLine("\nTaken:"); + Console.WriteLine(string.Join(", ", taken)); + ``` + +29. **查询并使用Skip跳过元素** + 跳过数组中的前3个元素,然后取出剩余的元素。 + + ```csharp + int[] numbers = { 1, 2, 3, 4, 5, 6,18,23,64,7,18,2,3 }; + var skipped = numbers.Skip(3).ToArray(); + Console.WriteLine("\nSkipped:"); + Console.WriteLine(string.Join(", ", skipped)); + ``` -- Gitee