LINQ 全名 Language-Integrated Query, 於 C# 3.0 引入, 讓程式設計師能使用一致性的語法來查詢不同的資料來源, 如查詢陣列、集合、DataSet、XML、SQL Server 資料庫等等
語法
var 變數 = from 範圍變數 in 集合 orderby 欄位名稱 where 條件 select 範圍變數[.欄位]
一些例子
using System;
using System.Collections.Generic;
using System.Linq;
string sentence = "I love cats";
string[] catNames = {"Lucky", "Bella", "Luna", "Oreo", "Simba", "Toby", "Loki", "Oscar"};
int[] numbers = {5, 6, 3, 2, 1, 7, 8, 234, 54, 14, 653, 3, 4, 5, 6, 7};
var getTheNumbers = from number in numbers
where number < 5
orderby number descending
select number;
Console.WriteLine(string.Join(",", getTheNumbers));
List<int> newNumbers = new List<int>();
foreach (var number in numbers)
{
if (number < 5)
{
newNumbers.Add(number);
}
}
Console.WriteLine(string.Join(",", newNumbers));
var catsWithA = from cat in catNames
where cat.Contains("a") && (cat.Length < 5)
select cat;
Console.WriteLine(string.Join(",", catsWithA));
internal class Person
{
private string name;
private int height;
private int weight;
private Gender gender;
public string Name {get; set;}
public int Height {get; set;}
public int Weight {get; set;}
public Gender Gender {get; set;}
public Person(string name, int height, int weight, Gender gender)
{
this.Name = name;
this.Height = height;
this.Weight = weight;
this.Gender = gender;
}
}
internal enum Gender
{
Male,
Female
}
List<Person> people = new List<Person>()
{
new Person("Tod", 180, 70, Gender.Female),
new Person("Kyle", 164, 77, Gender.Male),
new Person("Anna", 164, 77, Gender.Male)
};
var fourCharPeople = from p in people
where (p.Name.Length == 4)
orderby p.Weight
select p;
foreach (var item in fourCharPeople)
{
Console.WriteLine($"Name: {item.Name}, Weight: {item.Weight}");
}
從 c# 3.0 開始引入, 在方法範圍內, 可以使用關鍵字 var 宣告變數, 這是有隱含的 "type", 也是強型別, 但是由編譯器來判斷型別, 例
// 以下宣告功能一樣
var i = 100; // Implicitly typed
int i = 100; // Explicitly typed