C# LINQ笔记
from子句
- foreach语句命令式指定了按顺序一个个访问集合中的项。from子句只是声明式地规定集合中的每个项都要访问,并没有指定顺序。
- foreach在遇到代码时就执行其主体。from子句什么也不执行,只有在遇到访问查询变量的语句时才会执行。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace ConsoleApp2
{class Test{public static void Main(string[] args){int[] ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };var nums = from n in intswhere n > 7select n;foreach (var n in nums){Console.WriteLine(n);}Console.ReadKey();}}
}
运行结果
join子句
使用联结来结合两个或更多集合中的数据。
联结对象接受两个集合,然后创建一个临时的对象集合,每一个对象包含原始集合对象中的所有字段。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace ConsoleApp2
{class student{public int id;public string name;}class courseStudent{public string course;public int id;}class Test{static student[] students = new student[]{new student{ id = 1, name = "熊1" },new student{ id = 2, name = "熊2" },};static courseStudent[] courseStudents = new courseStudent[]{new courseStudent{ id = 1, course = "体育" },new courseStudent{ id = 2, course = "历史" },new courseStudent{ id = 3, course = "语文" },};public static void Main(string[] args){var names = from s in studentsjoin c in courseStudents on s.id equals c.idwhere c.course == "历史"select s.name;foreach (var item in names){Console.WriteLine(item);}Console.ReadKey();}}
}
运行结果
因为选修“历史”课程的是熊2,所以输出的是熊2:
orderby
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace ConsoleApp2
{class student{public int id;public string name;}class courseStudent{public string course;public int id;}class Test{static student[] students = new student[]{new student{ id = 1, name = "熊1" },new student{ id = 2, name = "熊2" },};static courseStudent[] courseStudents = new courseStudent[]{new courseStudent{ id = 1, course = "体育" },new courseStudent{ id = 2, course = "历史" },new courseStudent{ id = 3, course = "语文" },};public static void Main(string[] args){//匿名类型的对象数组var students2 = new[]{new { Name = "student1", Age = 1, Course = "体育" },new { Name = "student2", Age = 2, Course = "美术" },new { Name = "student3", Age = 3, Course = "历史" },new { Name = "student4", Age = 4, Course = "历史" },new { Name = "student5", Age = 5, Course = "历史" },new { Name = "student6", Age = 1, Course = "历史" },};var stu = from s in students2orderby s.Ageselect s;foreach (var student2 in stu)Console.WriteLine("{0},{1},{2}", student2.Name, student2.Age, student2.Course);Console.ReadKey();}}
}