1.基础查询linq
1.基本查询语法,查询所有偶数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[] arr = { 5,8,10,13,29,18,6}; var nums = from n in arr where n % 2 == 0 select n; //查询所有偶数 foreach(int n in nums)//遍历查询结果 { Console.WriteLine("偶数:{0}",n); } } }
运行结果: }
2.查询所有偶数并倒序排序,即:从大到小排using System;using System.Collections.Generic;
using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[] arr = { 5,8,10,13,29,18,6}; var nums = from n in arr where n % 2 == 0 orderby n descending //查询所有偶数并倒序排序,就是从大到小排序。 select n; //查询所有偶数 foreach(int n in nums)//遍历查询结果 { Console.WriteLine("偶数:{0}",n); } } } }
运行结果:
4.投影新对象
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Student { public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { //使用对象初始化器和集合初始化器来实例化学生列表 List<Student> listStu = new List<Student>(); { new Student(){Age=18,Name="莉莉",Sex="女"}; new Student(){Age=17,Name="小米",Sex="女"}; new Student() { Age = 28, Name = "小刚", Sex = "女" }; }; //查询并投影新对象,使用动态类型变量声明符和对象初始化器 var stus= from stu in listStu where stu.Age > 17 select new { StName=stu.Name,Stutex=stu.Sex}; //遍历新对象集合,并输出新对象的属性 foreach (var st in stus) { Console.WriteLine("{0},{1}",st.StName, st.Stutex); } } } }
5.获取集合对象的,长度大于7对象。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string[] arr = { "shenzhen","xian","nanjing","shanghai"}; IEnumerable<string> strs = from s in arr where s.Length > 7 select s; //获取对象集合 foreach (var s in strs) //循环对象 { Console.WriteLine(s); } } } }
运行结果:




浙公网安备 33010602011771号