Lanuague Intergarted Query
语言整合查询
我们可以使用它来查询一些信息,如我们查询数据库一样。
使用System.Linq命名空间
参考:https://www.bilibili.com/video/BV1TJ411h7cZ?t=2&p=230
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApp4
{
delegate void test(string s);
class Program
{
static void Main(string[] args)
{
int[] numbers = {1, 3, 5, 16, 8, 1, 0, 5, 7};//实现了IEnumerable 的数据可以使用LINQ
//1.直接使用语句
var numQurey1 = from num in numbers
where num % 2 == 0 //查询条件
orderby num //排序
select num; //输出
foreach(var i in numQurey1)//这个语句在使用到的时候才会被执行
{
Console.Write(i + " ");
}
//2.使用方法
var numQurey2 = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
foreach (var i in numQurey2)//这个语句在使用到的时候才会被执行
{
Console.Write(i + " ");
}
//用到的查询关键字和方法还有很多
//方法:numQurey2.Count() 获得长度 numQurey2.ToList() 转换为列表
// numQurey2.ToArray() 转换为数组 这些函数执行时会立即执行语句
//关键字:
//where 使用 || && 等操作符来控制条件 如:x < 0 || x>5
//orderby num descending 获得的结果降序排列 orderby num ascending 获得的结果降序排列
//group 查询的结果分组
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { Name = "Jack", City = "Beijing" });
customers.Add(new Customer() { Name = "LiLei", City = "Beijing" });
customers.Add(new Customer() { Name = "WangMei", City = "Shanghai" });
var queryCustomers = from c in customers
group c by c.City;
foreach(var i in queryCustomers)
{
Console.WriteLine();
Console.WriteLine(i.Key);//Key 就是分组的键值
foreach(var j in i)
{
Console.WriteLine(" " + j.Name + " " + j.City);
}
}
//join 合并两个数据
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { Name = "Jack", ID = 101 });
employees.Add(new Employee() { Name = "Emily", ID = 102 });
var queryJoin = from c in customers
join e in employees on c.Name equals e.Name
select new { PersonName = c.Name, PersonID = e.ID, PerCity = c.City };
foreach(var i in queryJoin)
{
Console.WriteLine();
Console.WriteLine(i.PersonName + " " + i.PersonID + " " + i.PerCity);
}
//into group的结果进行打包
var queryCustomers2 = from c in customers
group c by c.City into customerGroup
where customerGroup.Count() >= 2
select new { city = customerGroup.Key, number = customerGroup.Count() };
foreach(var i in queryCustomers2)
{
Console.WriteLine();
Console.WriteLine(i.city + " " + i.number);
}
//let 可以存储中间变量
string[] strings = { "I am hansome", "Who are you", "Who I am" };
var stringQuery = from s in strings
let words = s.Split()
from word in words
let w = word.ToUpper()
select w;
Console.WriteLine();
foreach (var i in stringQuery)
{
Console.WriteLine(i);
}
}
}
class Customer
{
public string Name
{
get;
set;
}
public string City
{
get;
set;
}
}
class Employee
{
public string Name
{
get;
set;
}
public int ID
{
get;
set;
}
}
}
当然更多的用法需要百度自行查询。