Lanuague Intergarted Query
語言整合查詢
我們可以使用它來查詢一些信息,如我們查詢數(shù)據(jù)庫一樣伞租。
使用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};//實(shí)現(xiàn)了IEnumerable 的數(shù)據(jù)可以使用LINQ
//1.直接使用語句
var numQurey1 = from num in numbers
where num % 2 == 0 //查詢條件
orderby num //排序
select num; //輸出
foreach(var i in numQurey1)//這個(gè)語句在使用到的時(shí)候才會(huì)被執(zhí)行
{
Console.Write(i + " ");
}
//2.使用方法
var numQurey2 = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
foreach (var i in numQurey2)//這個(gè)語句在使用到的時(shí)候才會(huì)被執(zhí)行
{
Console.Write(i + " ");
}
//用到的查詢關(guān)鍵字和方法還有很多
//方法:numQurey2.Count() 獲得長(zhǎng)度 numQurey2.ToList() 轉(zhuǎn)換為列表
// numQurey2.ToArray() 轉(zhuǎn)換為數(shù)組 這些函數(shù)執(zhí)行時(shí)會(huì)立即執(zhí)行語句
//關(guān)鍵字:
//where 使用 || && 等操作符來控制條件 如:x < 0 || x>5
//orderby num descending 獲得的結(jié)果降序排列 orderby num ascending 獲得的結(jié)果降序排列
//group 查詢的結(jié)果分組
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 合并兩個(gè)數(shù)據(jù)
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的結(jié)果進(jìn)行打包
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 可以存儲(chǔ)中間變量
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;
}
}
}
當(dāng)然更多的用法需要百度自行查詢裸弦。