LINQ(語言集成查詢)使用案例
概念
語言集成查詢 (LINQ) 是一系列直接將查詢功能集成到 C# 語言的技術(shù)統(tǒng)稱。
數(shù)據(jù)查詢歷來都表示為簡單的字符串,沒有編譯時類型檢查或 IntelliSense 支持。 此外,需要針對每種類型的數(shù)據(jù)源了解不同的查詢語言:SQL 數(shù)據(jù)庫、XML 文檔、各種 Web 服務(wù)等。
借助 LINQ,查詢成為了最高級的語言構(gòu)造,就像類、方法和事件一樣。 可以使用語言關(guān)鍵字和熟悉的運算符針對強類型化對象集合編寫查詢。 LINQ 系列技術(shù)提供了針對對象 (LINQ to Objects)、關(guān)系數(shù)據(jù)庫 (LINQ to SQL) 和 XML (LINQ to XML) 的一致查詢體驗。
對于編寫查詢的開發(fā)者來說,LINQ 最明顯的“語言集成”部分就是查詢表達式。
查詢表達式采用聲明性查詢語法編寫而成。 使用查詢語法,可以用最少的代碼對數(shù)據(jù)源執(zhí)行篩選、排序和分組操作。 可使用相同的基本查詢表達式模式來查詢和轉(zhuǎn)換 SQL 數(shù)據(jù)庫、ADO .NET 數(shù)據(jù)集、XML 文檔和流以及 .NET 集合中的數(shù)據(jù)。
在 C# 中可為以下對象編寫 LINQ 查詢:SQL Server 數(shù)據(jù)庫、XML 文檔、ADO.NET 數(shù)據(jù)集以及支持 IEnumerable 或泛型 IEnumerable 接口的任何對象集合。 此外,第三方也為許多 Web 服務(wù)和其他數(shù)據(jù)庫實現(xiàn)提供了 LINQ 支持。
實現(xiàn)案例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkConsole
{
class Program
{
static void Main(string[] args)
{
//-------------最基本的簡單查詢----------------//
List<int> numbers = new List<int>() { 1,2,3,4,5,6,7,8,9,10};
var numQuery = from num in numbers
where num % 2 == 0
select num;
foreach (var num in numQuery)
{
Console.WriteLine("{0,1}", num);
}
//-------------讀取List<>中的句子----------------//
FormExpDemo2();
//-------------復(fù)合form子句----------------//
FormExpDemo();
//-------------多個from句子---------------//
FormExpDemo3();
//-------------where-------------------//
WhereExpDemo();
//-------------select------------------//
SelectDemo();
//-------------group--------------------//
GroupDemo();
//-------------into------------------------//
IntoDemo();
//--------------OrderBy--------------------//
ThenByDemo();
//--------------let----------------------//
LetDemo();
//--------------join--------------------//
JoinDemo();
Console.ReadLine();
}
public class CustomerInfo
{
public string Name { get; set; }
public int Age { get; set; }
public string Tel { get; set; }
public List<string> telTable { get; set; }
}
public static void FormExpDemo2()
{
//
List<CustomerInfo> customers = new List<CustomerInfo>
{
new CustomerInfo{ Name = "歐陽曉曉",Age = 35,Tel = "123"},
new CustomerInfo{ Name = "上官飄飄",Age = 17,Tel = "456"},
new CustomerInfo{ Name = "諸葛菲菲",Age = 23,Tel = "789"}
};
var query = from ci in customers
where ci.Age > 20
select ci;
foreach (var ci in query)
{
Console.WriteLine("姓名:{0}年齡:{1}電話:{2}", ci.Name, ci.Age, ci.Tel);
}
}
//復(fù)合from子句 // 相當(dāng)于兩個for循環(huán)而已
private static void FormExpDemo()
{
List<CustomerInfo> customers = new List<CustomerInfo>
{
new CustomerInfo { Name = "歐陽小小",Age= 35,telTable = new List<string> {"123","234"} },
new CustomerInfo { Name = "上官飄飄",Age= 35,telTable = new List<string> {"456","567"} },
new CustomerInfo { Name = "諸葛菲菲",Age= 35,telTable = new List<string> {"789","456"} },
};
//查詢包含電話號碼456的客戶
var query = from ci in customers
from tel in ci.telTable
where tel.IndexOf("456") > -1
select ci;
foreach (var ci in query)
{
Console.WriteLine("姓名:{0}年齡:{1}", ci.Name, ci.Age);
foreach (var tel in ci.telTable)
{
Console.WriteLine(" 電話:{0}", tel);
}
}
}
//多個from子句,和復(fù)合子句看起來是一樣的,其實不一樣,一個是單個數(shù)據(jù)源中的子元素的集合,一個是對多個數(shù)據(jù)源進行查詢
private static void FormExpDemo3()
{
List<CustomerInfo> customers = new List<CustomerInfo>
{
new CustomerInfo{ Name = "歐陽曉曉",Age = 35,Tel = "123"},
new CustomerInfo{ Name = "上官飄飄",Age = 77,Tel = "456"},
new CustomerInfo{ Name = "諸葛菲菲",Age = 23,Tel = "789"}
};
List<CustomerInfo> customers2 = new List<CustomerInfo>
{
new CustomerInfo{ Name = "令狐沖",Age = 25,Tel = "123"},
new CustomerInfo{ Name = "東方不敗",Age = 15,Tel = "456"},
new CustomerInfo{ Name = "任盈盈",Age = 13,Tel = "789"}
};
//在customers 中尋找年齡大于20的客戶
//在customenrs中尋找年齡小于30歲的客戶
var query = from custo in customers
where custo.Age > 20
from custo2 in customers2
where custo2.Age < 30
select new { custo, custo2 };
foreach (var ci in query)
{
Console.WriteLine("{0},{1}", ci.custo.Name, ci.custo2.Name);//這樣得到的是一個交叉聯(lián)結(jié)表,有點類似于SQL中的笛卡爾沉積
}
}
//where子句查詢
//where就是用來篩選元素的,除了開始和結(jié)束位置,where可以在任意位置使用,
//一個LIKQ語句中可以有where子句,也可以沒有,可以有一個,也可以有多個。
//多個where子句之間的關(guān)系相當(dāng)于邏輯“與”,每個子句中又可以包含多個用“謂詞”鏈接的邏輯表達式,&&,或者||
private static void WhereExpDemo()
{
List<CustomerInfo> clist = new List<CustomerInfo>
{
new CustomerInfo{ Name="歐陽曉曉", Age=35, Tel ="1330708****"},
new CustomerInfo{ Name="上官飄飄", Age=17, Tel ="1592842****"},
new CustomerInfo{ Name="令狐沖", Age=23, Tel ="1380524****"}
};
//可以查詢符合多個條件的人(名字是三個字或者姓令的,但年齡必須大于20)
var query = from custo in clist
where (custo.Name.Length == 3 || custo.Name.Substring(0, 1) == "令") && custo.Age > 20
select custo;//select 也可以改成,比如custo.Name。或者用一個函數(shù),把變量傳出去
foreach (var ci in query)
{
Console.WriteLine("姓名:{0}年齡:{1}電話:{2}", ci.Name, ci.Age, ci.Tel);
}
//where中使用自定義函數(shù),查詢?nèi)齻€字并且姓令的客戶
var query2 = from custo in clist
where (custo.Name.Length == 3 && ChechName(custo.Name))
select custo;
foreach (var ci in query2)
{
Console.WriteLine("姓名:{0}年齡:{1}電話:{2}", ci.Name, ci.Age, ci.Tel);
}
}
private static bool ChechName(string name)
{
if (name.Substring(0, 1) == "令")
return true;
else
return false;
}
//select 用法舉例
private static void SelectDemo()
{
List<CustomerInfo> clist = new List<CustomerInfo>
{
new CustomerInfo{ Name="歐陽曉曉", Age=35, Tel ="1330708****"},
new CustomerInfo{ Name="上官飄飄", Age=17, Tel ="1592842****"},
new CustomerInfo{ Name="令狐沖", Age=23, Tel ="1380524****"}
};
string[] names = { "令狐沖", "任盈盈", "楊過", "小龍女", "歐陽小夏", "歐陽曉曉" };
//查詢在給定謂詞數(shù)組里存在的客戶
var query = from custo in clist
where custo.Age < 30
select new MyCustomerInfo { Name = custo.Name, Tel = custo.Tel };
foreach (var ci in query)
{
Console.WriteLine("姓名:{0}電話:{1}類型{2}", ci.Name, ci.Tel, ci.GetType().FullName);
}
}
public class MyCustomerInfo
{
public string Name { get; set; }
public string Tel { get; set; }
}
//-------------------Group----------------------//
static List<CustomerInfo> clist = new List<CustomerInfo>
{
new CustomerInfo{ Name="歐陽曉曉", Age=35, Tel ="1330708"},
new CustomerInfo{ Name="上官飄飄", Age=17, Tel ="1592842"},
new CustomerInfo{ Name="歐陽錦鵬", Age=35, Tel ="1330708"},
new CustomerInfo{ Name="上官無忌", Age=23, Tel ="1380524"}
};
private static void GroupDemo()
{
//按照名字的前兩個字進行分組
var query = from custo in clist
group custo by custo.Name.Substring(0, 2);
foreach (IGrouping<string, CustomerInfo> group in query)
{
Console.WriteLine("分組鍵:{0}", group.Key);
foreach (var ci in group)
{
Console.WriteLine("姓名:{0}電話:{1}", ci.Name, ci.Tel);
}
Console.WriteLine("*********************");
}
//可以知道group子句返回的是一個IGrouping<TKey,TElement>泛型接口的對象集合
//TKey是鍵的對象類型,在用于group子句的時候,編譯器會識別數(shù)據(jù)類型,用于存儲分組的鍵值,也就是根據(jù)什么分的組
//TElement是指的對象類型用于分配儲存結(jié)果,變量基于這個接口的類型就是遍歷這個值,也就是分組的對象
}
//----------------into子句---------------//
private static void IntoDemo()
{
//into提供了一個臨時標(biāo)識符,它儲存了into子句前面的查詢內(nèi)容,使他后面的子句可以方便使用,再次查詢投影
var query = from custo in clist
group custo by custo.Name.Substring(0, 2) into gpcustomer
orderby gpcustomer.Key descending //排序,
select gpcustomer;
Console.WriteLine("into用于group子句");
foreach (var group in query)
{
Console.WriteLine("分組見:{0}", group.Key);
foreach (var ci in group)
{
Console.WriteLine("姓名:{0}電話:{1}", ci.Name, ci.Tel);
}
Console.WriteLine("***********************");
}
var query2 = from custo in clist
select new { NewName = custo.Name, NewAge = custo.Age } into newCustomer
orderby newCustomer.NewAge
select newCustomer;
Console.WriteLine("into用于select子句");
foreach (var ci in query2)
{
Console.WriteLine("{0}年齡:{1}", ci.NewName, ci.NewAge);
}
}
//---------------排序子句--------------------//
//LINQ可以按元素的一個或者多個屬性對元素進行排序,表達式的排序方式分為OrderBy、OrderByDescending、ThenBy、ThenByDescending
//加了Descending的就是降序,沒有加的就是升序
private static void ThenByDemo()
{
List<CustomerInfo> clist = new List<CustomerInfo>
{
new CustomerInfo{ Name="歐陽曉曉 ", Age=35, Tel ="1330708****"},
new CustomerInfo{ Name="上官飄飄 ", Age=17, Tel ="1592842****"},
new CustomerInfo{ Name="郭靖 ", Age=17, Tel ="1330708****"},
new CustomerInfo{ Name="黃蓉 ", Age=17, Tel ="1300524****"}
};
//按照年齡升序,再按照名字的字?jǐn)?shù)次要排序
var query = from customer in clist
orderby customer.Age, customer.Name.Length
select customer;
Console.WriteLine("按年齡排列,按名字字?jǐn)?shù)進行次要排序");
foreach (var ci in query)
{
Console.WriteLine("姓名:{0} 年齡:{1} 電話:{2}",ci.Name, ci.Age, ci.Tel);
}
//按年齡降序,再按名字的字?jǐn)?shù)降序次要排列
var query2 = from customer in clist
orderby customer.Age descending , customer.Name.Length descending
select customer;
Console.WriteLine("\n按年齡排列,按名字字?jǐn)?shù)進行降序次要排列");
foreach (var ci in query2)
{
Console.WriteLine("姓名:{0} 年齡:{1} 電話:{2}", ci.Name, ci.Age, ci.Tel);
}
}
//--------------let子句---------------------//
private static void LetDemo()
{
var query = from custo in clist
let g = custo.Name.Substring(0, 1)//let建立一個范圍變量,在where中使用
where g == "歐" || g == "上"http://也可以不寫,寫成customer.Name.Substring(0, 1) == "郭" || customer.Name.Substring(0, 1) == "黃"
select custo;
foreach (var ci in query)
{
Console.WriteLine("姓名:{0} 年齡:{1} 電話:{2}", ci.Name, ci.Age, ci.Tel);
}
}
//-------------join子句-------------------//
private static void JoinDemo()
{
//如果兩個數(shù)據(jù)源中的屬性可以進行相等比較,那么兩個句子可以用join進行關(guān)聯(lián),比較的符號為equal,而不是==
List<CustomerInfo> clist = new List<CustomerInfo>
{
new CustomerInfo{ Name="歐陽曉曉", Age=35, Tel ="1330708****"},
new CustomerInfo{ Name="上官飄飄", Age=17, Tel ="1592842****"},
new CustomerInfo{ Name="郭靖", Age=17, Tel ="1330708****"},
new CustomerInfo{ Name="黃蓉", Age=17, Tel ="1300524****"}
};
List<CustomerTitle> titleList = new List<CustomerTitle>
{
new CustomerTitle{ Name="歐陽曉曉", Title="歌手"},
new CustomerTitle{ Name="郭靖", Title="大俠"},
new CustomerTitle{ Name="郭靖", Title="洪七公徒弟"},
new CustomerTitle{ Name="黃蓉", Title="才女"},
new CustomerTitle{ Name="黃蓉", Title="丐幫幫主"}
};
//根據(jù)姓名進行內(nèi)部聯(lián)結(jié)
var query = from customer in clist
join title in titleList
on customer.Name equals title.Name
select new { Name = customer.Name, Age = customer.Age, Title = title.Title };
foreach (var ci in query)
{
Console.WriteLine("姓名:{0} 年齡:{1}{2}", ci.Name, ci.Age, ci.Title);
}
//根據(jù)姓名進行分組聯(lián)結(jié)
Console.WriteLine("\n根據(jù)姓名進行分組聯(lián)結(jié)");
var query2 = from customer in clist
join title in titleList
on customer.Name equals title.Name into tgroup
select new { Name = customer.Name, Titles = tgroup };
foreach (var g in query2)
{
Console.WriteLine(g.Name);
foreach (var g2 in g.Titles)
{
Console.WriteLine(" {0}", g2.Title);
}
}
//根據(jù)姓名進行 左外部聯(lián)結(jié)
Console.WriteLine("\n左外部聯(lián)結(jié)");
var query3 = from customer in clist
join title in titleList
on customer.Name equals title.Name into tgroup
from subTitle in tgroup.DefaultIfEmpty()
select new { Name = customer.Name, Title = (subTitle == null ? "空缺" : subTitle.Title) };
foreach (var ci in query3)
{
Console.WriteLine("姓名:{0} ", ci.Name, ci.Title);
}
}
public class CustomerTitle
{
public string Name { get; set; }
public string Title { get; set; }
}
}
}到此這篇關(guān)于LINQ(語言集成查詢)使用案例的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript函數(shù)中執(zhí)行c#函數(shù)的方法
這篇文章主要介紹了javascript和c#函數(shù)和變量互相調(diào)用的方法,大家參考使用吧2014-01-01
C#調(diào)用百度翻譯實現(xiàn)翻譯HALCON的示例
HALCON示例程序的描述部分一直是英文的,看起來很不方便。本文就使用百度翻譯實現(xiàn)翻譯HALCON,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06
深入學(xué)習(xí)C#網(wǎng)絡(luò)編程之HTTP應(yīng)用編程(下)
這篇文章主要介紹了深入學(xué)習(xí)C#網(wǎng)絡(luò)編程之HTTP應(yīng)用編程的相關(guān)知識,文中講解的非常詳細,幫助大家更好的學(xué)習(xí)c#網(wǎng)絡(luò)編程,感興趣的朋友可以了解下2020-06-06

