從LINQ開始之LINQ to Objects(上)
LINQ概述
LINQ,語言集成查詢(Language Integrated Query),它允許使用C#或VB代碼以查詢數據庫相同的方式來操作不同的數據源。
LINQ體系結構
從上圖可以看出,LINQ總共包括五個部分:LINQ to Objects、LINQ to DataSets、LINQ to SQL、LINQ to Entities、LINQ to XML。
LINQ to Objects:對內存中集合的操作
LINQ to DataSets:對數據集Datatable的操作
LINQ to SQL:對SQL Server數據源的操作,微軟把開發的重點從LINQ to SQL轉移到了LINQ to Entities並且宣布LINQ to SQL不再提供更新
LINQ to Entities:是 Entity Framework的一部分並且取代LINQ to SQL作為在數據庫上使用 LINQ的標準機制
LINQ to XML:對XML數據源的操作
LINQ的語法
下面是一個簡單的示例,查詢一個int數組中小於5的元素,並按照從小到大的順序排列:
int[] arr = new int[] { 1, 4, 2, 6, 7, 9, 5, 1, 2, 4 }; var query = from r in arr where r < 5 orderby r select r; foreach (var item in query) { Console.WriteLine(item); } Console.ReadLine();
由此示例可以看出:LINQ查詢表達式以from子句開頭,以select子句結束。在兩個子句之間,可以使用where、orderby等查詢操作符。
LINQ有兩種語法:Lambda語法和Query語法,編譯器會在程序編譯時轉換LINQ查詢,以調用相應的擴展方法。
以下是LINQ表達式結構示意圖:
引用自百度百科
LINQ to Objects
LINQ to Objects中的擴展方法在System.Core程序集的System.Linq命名空間中定義。
Enumerable類定義的標準查詢操作符:
下面介紹使用這些操作符的示例:
首先,我們需要創建基本的實體類Employee:
/// <summary> /// 員工類 /// </summary> public class Employee { //員工編號 public string EmployeeId { get; private set; } //員工姓名 public string EmployeeName { get; private set; } //年齡 public int Age { get; private set; } //入職日期 public DateTime EntryDate { get; private set; } //性別 public string Sex { get; private set; } //部門 public string Department { get; private set; } //薪水 public int Salary { get; private set; } //愛好 public IEnumerable<string> Hobby { get; private set; } public Employee(string employeeId, string employeeName, int age, DateTime entryDate, Sex sex, Department department, int salary, IEnumerable<string> hobby) { this.EmployeeId = employeeId; this.EmployeeName = employeeName; this.Age = age; this.EntryDate = entryDate; this.Sex = sex.ToString(); this.Department = department.ToString(); this.Salary = salary; this.Hobby = hobby; } } //性別 public enum Sex { Male, Female } //部門 public enum Department { HR, IT, PD, FD, QC, MD }
然後,創建列表employees保存10名員工的基本信息:
List<Employee> employees = new List<Employee>()
{
new Employee("001","Mike",32,new DateTime(2016,2,20),Sex.Male,Department.IT,200000,new string[] { "swimming","shopping"}),
new Employee("002","Jack",38,new DateTime(2007,5,12),Sex.Male,Department.HR,409989,new string[] { "reading"}),
new Employee("003","Adolph",25,new DateTime(2017,3,23),Sex.Male,Department.IT,100000,new string[] { "play computer games","watch TV","listen to music"}),
new Employee("004","Antony",30,new DateTime(2010,11,20),Sex.Male,Department.FD,320000, new string[] { "play chess","run"}),
new Employee("005","Asa",28,new DateTime(2014,10,10),Sex.Female,Department.FD,120000,new string[] { "shopping"}),
new Employee("006","Bernie",31,new DateTime(2008,4,5),Sex.Male,Department.PD,220000,new string[] { "play basketball"}),
new Employee("007","Carl",26,new DateTime(2015,1,30),Sex.Male,Department.QC,100000,new string[] { "play chess","go fishing"}),
new Employee("008","Duncan",30,new DateTime(2009,6,9),Sex.Male,Department.MD,250000,new string[] { "play computer games"}),
new Employee("009","Aimee",24,new DateTime(2017,1,20),Sex.Female,Department.HR,80000,new string[] { "reading","run"}),
new Employee("010","Cassie",31,new DateTime(2014,3,3),Sex.Female,Department.IT,350000,new string[] { "watch TV" })
};
1)篩選操作符(Where、OfType<TResult>)
Where:根據表達式函數過濾元素
//查詢年齡大於30歲,IT或HR部門所有員工的編號及姓名
var filter = from r in employees
where r.Age > 30 && (r.Department == Department.IT.ToString() || r.Department == Department.HR.ToString())
select r;
foreach (var item in filter)
{
Console.WriteLine("EmployId: " +item.EmployeeId + " EmployeeName: " + item.EmployeeName);
}
//******************************Output*******************************
//EmployId: 001 EmployeeName: Mike
//EmployId: 002 EmployeeName: Jack
//EmployId: 010 EmployeeName: Cassie
//*******************************************************************
OfType<TResult>:類型篩選
//篩選出指定數組中所有int類型的元素
object[] data = { "One", 2, 3, "Four", "Five", 6 };
var typeFilter = data.OfType<int>();
foreach (var item in typeFilter)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//2
//3
//6
//*******************************************************************
2)投射操作符(Select、SelectMany)
Select:根據選擇器函數選擇的結果值投射到新的類型元素上
SelectMany:C#編譯器把復合的from子句和LINQ查詢轉換為SelectMany擴展方法,用於叠代序列的序列。
//查找個人愛好中有reading的員工的姓名
var doubleFrom = from r in employees
from h in r.Hobby
where h == "reading"
select r.EmployeeName;
foreach (var item in doubleFrom)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//Jack
//Aimee
//*******************************************************************
//--------------------------強勢分隔符--------------------------------
//使用SelectMany擴展方法返回個人愛好中有reading的員工的姓名
var selectMany = employees.
SelectMany(r => r.Hobby,
(r, h) => new { Employee = r, Hobby = h }).
Where(r => r.Hobby == "reading").
Select(r => r.Employee.EmployeeName);
foreach (var item in selectMany)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//Jack
//Aimee
//*******************************************************************
3)排序操作符(OrderBy、ThenBy、OrderByDescending、ThenByDescending、Reverse)
OrderBy、OrderByDescending:升序排序、降序排序
ThenBy、ThenByDescending:如果第一次排序有元素相同,進行第二次排序(使用LINQ查詢時只需把需要排序的關鍵字用逗號隔開)
//按照年齡從大到小排序,如果年齡相同,則按照員工編號正向排序,輸出員工的編號、姓名、年齡,
var orderBy = from o in employees
orderby o.Age descending, o.EmployeeId
select o;
foreach (var item in orderBy)
{
Console.WriteLine("EmployeeId: " + item.EmployeeId + " EmployeeName:" + item.EmployeeName + " Age:" + item.Age);
}
//******************************Output*******************************
//EmployeeId: 002 EmployeeName: Jack Age:38
//EmployeeId: 001 EmployeeName: Mike Age:32
//EmployeeId: 006 EmployeeName: Bernie Age:31
//EmployeeId: 010 EmployeeName: Cassie Age:31
//EmployeeId: 004 EmployeeName: Antony Age:30
//EmployeeId: 008 EmployeeName: Duncan Age:30
//EmployeeId: 005 EmployeeName: Asa Age:28
//EmployeeId: 007 EmployeeName: Carl Age:26
//EmployeeId: 003 EmployeeName: Adolph Age:25
//EmployeeId: 009 EmployeeName: Aimee Age:24
//*******************************************************************
//--------------------------強勢分隔符--------------------------------
//使用ThenBy擴展方法實現年齡相同,按員工編號正向排序
var thenBy = employees
.OrderByDescending(t => t.Age)
.ThenBy(t => t.EmployeeId)
.Select(t => "EmployeeId: " + t.EmployeeId + " EmployeeName:" + t.EmployeeName + " Age:" + t.Age);
foreach (var item in thenBy)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//EmployeeId: 002 EmployeeName: Jack Age:38
//EmployeeId: 001 EmployeeName: Mike Age:32
//EmployeeId: 006 EmployeeName: Bernie Age:31
//EmployeeId: 010 EmployeeName: Cassie Age:31
//EmployeeId: 004 EmployeeName: Antony Age:30
//EmployeeId: 008 EmployeeName: Duncan Age:30
//EmployeeId: 005 EmployeeName: Asa Age:28
//EmployeeId: 007 EmployeeName: Carl Age:26
//EmployeeId: 003 EmployeeName: Adolph Age:25
//EmployeeId: 009 EmployeeName: Aimee Age:24
//*******************************************************************
Revise:使用擴展方法反轉集合中的元素順序
//按照年齡從大到小排序後再反轉元素的順序
var reverse = employees
.OrderByDescending(r => r.Age)
.Reverse()
.Select(r => "EmployeeId: " + r.EmployeeId + " EmployeeName:" + r.EmployeeName + " Age:" + r.Age);
foreach (var item in reverse)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//EmployeeId: 009 EmployeeName: Aimee Age:24
//EmployeeId: 003 EmployeeName: Adolph Age:25
//EmployeeId: 007 EmployeeName: Carl Age:26
//EmployeeId: 005 EmployeeName: Asa Age:28
//EmployeeId: 008 EmployeeName: Duncan Age:30
//EmployeeId: 004 EmployeeName: Antony Age:30
//EmployeeId: 010 EmployeeName: Cassie Age:31
//EmployeeId: 006 EmployeeName: Bernie Age:31
//EmployeeId: 001 EmployeeName: Mike Age:32
//EmployeeId: 002 EmployeeName: Jack Age:38
//*******************************************************************
4)連接操作符(Join、GroupJoin)
為了完成這部分的示例,我們需要準備新的實體類和列表
/// <summary>
/// 部門信息
/// </summary>
public class DepartmentInfo
{
//部門編號
public string DepartmentId { get; private set; }
//部門名稱
public string DepartmentName { get; private set; }
//部門總監
public string Director { get; private set; }
public DepartmentInfo(string departmentId, string departmentName, string director)
{
this.DepartmentId = departmentId;
this.DepartmentName = departmentName;
this.Director = director;
}
}
/// <summary>
/// 傑出團隊
/// </summary>
public class OutstandingTeam
{
public int Year { get; private set; }
public string Department { get; private set; }
public OutstandingTeam(int year, string department)
{
this.Year = year;
this.Department = department;
}
}
創建列表departmentInfo保存各部門的信息
List<DepartmentInfo> deparmentInfo = new List<DepartmentInfo>()
{
new DepartmentInfo("001","HR","Oliver"),
new DepartmentInfo("002","IT","Oscar"),
new DepartmentInfo("003","PD","ELLA"),
new DepartmentInfo("004","FD","Alice"),
new DepartmentInfo("005","QC","Kai")
};
創建列表outstandingTeams保存2010年起獲得傑出團隊的部門
List<OutstandingTeam> outstandingTeams = new List<OutstandingTeam>()
{
new OutstandingTeam(2010,"IT"),
new OutstandingTeam(2011,"FD"),
new OutstandingTeam(2012,"HR"),
new OutstandingTeam(2013,"IT"),
new OutstandingTeam(2014,"QC"),
new OutstandingTeam(2015,"HR"),
new OutstandingTeam(2016,"HR"),
new OutstandingTeam(2017,"MD")
};
Join:根據特定的條件合並兩個數據源
//查詢員工的姓名,部門以及該部門的總監
var join = from j in employees
join d in deparmentInfo
on j.Department equals d.DepartmentName
select new
{
j.EmployeeName,
j.Department,
d.Director
};
foreach (var item in join)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " Department:" + item.Department + " Director:" + item.Director);
}
//******************************Output*******************************
//EmployeeName: Mike Department:IT Director:Oscar
//EmployeeName: Jack Department:HR Director:Oliver
//EmployeeName: Adolph Department:IT Director:Oscar
//EmployeeName: Antony Department:FD Director:Alice
//EmployeeName: Asa Department:FD Director:Alice
//EmployeeName: Bernie Department:PD Director:ELLA
//EmployeeName: Carl Department:QC Director:Kai
//EmployeeName: Aimee Department:HR Director:Oliver
//EmployeeName: Cassie Department:IT Director:Oscar
//*******************************************************************
這時候我們會發現,輸出的內容裏面少了員工Duncan的信息,檢查後發現,原來deparmentInfo沒有添加MD部門的相關信息,此時希望查詢所有員工,若匹配不到該部門信息,Director返回N/A。
//查詢員工的姓名,部門以及該部門的總監,若匹配不到該部門信息,Director返回N/A
var leftjoin = from j in employees
join d in deparmentInfo
on j.Department equals d.DepartmentName into jd
from d in jd.DefaultIfEmpty()
select new
{
j.EmployeeName,
j.Department,
Director = d == null ? "N/A" : d.Director
};
foreach (var item in leftjoin)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " Department:" + item.Department + " Director:" + item.Director);
}
//******************************Output*******************************
//EmployeeName: Mike Department:IT Director:Oscar
//EmployeeName: Jack Department:HR Director:Oliver
//EmployeeName: Adolph Department:IT Director:Oscar
//EmployeeName: Antony Department:FD Director:Alice
//EmployeeName: Asa Department:FD Director:Alice
//EmployeeName: Bernie Department:PD Director:ELLA
//EmployeeName: Carl Department:QC Director:Kai
//EmployeeName: Duncan Department:MD Director:N/A
//EmployeeName: Aimee Department:HR Director:Oliver
//EmployeeName: Cassie Department:IT Director:Oscar
//*******************************************************************
GroupJoin:基於鍵相等對兩個序列的元素進行關聯並對結果進行分組。
//查找每個部門獲得傑出團隊的年份
var groupJoin = from d in deparmentInfo
join o in outstandingTeams on d.DepartmentName equals o.Department into g
select new
{
DepartmentName = d.DepartmentName,
Years = g
};
foreach (var item in groupJoin)
{
Console.WriteLine("Department:" + item.DepartmentName);
if (item.Years.Count() == 0)
{
Console.WriteLine("Never won the award");
}
foreach (var champions in item.Years)
{
Console.WriteLine(champions.Year);
}
}
//******************************Output*******************************
//Department: HR
//2012
//2015
//2016
//Department: IT
//2010
//2013
//Department: PD
// Never won the award
// Department:FD
//2011
//Department: QC
//2014
//*******************************************************************
5)組合操作符(GroupBy、ToLookup)
GroupBy:根據關鍵字值對查詢結果進行分組。
//查詢每個部門及人數
var groupBy = from e in employees
group e by e.Department into g
select new
{
g.Key,
Count = g.Count()
};
foreach (var item in groupBy)
{
Console.WriteLine("Department: " + item.Key + " Count: " + item.Count);
}
//******************************Output*******************************
//Department: IT Count: 3
//Department: HR Count: 2
//Department: FD Count: 2
//Department: PD Count: 1
//Department: QC Count: 1
//Department: MD Count: 1
//*******************************************************************
ToLookup:通過創建一對多的字典來組合元素
//使用ToLookup實現愛好閱讀的員工姓名
var toLookup = (from e in employees
from h in e.Hobby
select new
{
Hobby = h,
Name = e.EmployeeName
}).ToLookup(he => he.Hobby, he => he.Name);
if (toLookup.Contains("reading"))
{
foreach (var item in toLookup["reading"])
{
Console.WriteLine(item);
}
}
//******************************Output*******************************
//Jack
//Aimee
//*******************************************************************
6)限定操作符(Any、All、Contains)
Any:是否包含滿足條件的元素
//是否有小於20歲的員工
bool any = employees.Any(r => r.Age < 20);
Console.WriteLine(any);
//******************************Output*******************************
//False
//*******************************************************************
ALL:是否所有元素都滿足條件
//是否所有員工都大於20歲
bool all = employees.All(r => r.Age > 20);
Console.WriteLine(all);
//******************************Output*******************************
//True
//*******************************************************************
Contains:檢索某個元素是否在集合中
//員工列表中是否包含david
Employee david = new Employee("011", "David", 28, new DateTime(2017, 5, 21), Sex.Male, Department.IT, 100000, new string[] { "run" });
employees.Add(david);
bool contains = employees.Contains(david);
Console.WriteLine(contains);
//******************************Output*******************************
//True
//*******************************************************************
7)分區操作符(Take、Skip、TakeWhile、SkipWhile)
Take:從集合中提取指定數量的元素
Skip:跳過集合中指定數量的元素
//忽略薪水最高的5位,查詢剩余部分薪水最高的員工姓名及薪水
var skip = (from e in employees
orderby e.Salary descending
select e).Skip(5).Take(1);
foreach (var item in skip)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " Salary: " + item.Salary);
}
//******************************Output*******************************
//EmployeeName: Mike Salary: 200000
//*******************************************************************
TakeWhile:提取條件為真時的元素
//取集合中滿足條件salary大於1000000之前的所有員工的姓名和薪水
var takeWhile = (from e in employees
select e).TakeWhile(r => r.Salary > 100000);
foreach (var item in takeWhile)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " Salary: " + item.Salary);
}
//******************************Output*******************************
//EmployeeName: Mike Salary: 200000
//EmployeeName: Jack Salary: 409989
//*******************************************************************
SkipWhere:跳過集合中滿足條件的元素,當條件不成立時返回剩余的所有元素
//跳過集合中滿足條件salary大於100000的元素,當條件不成立時返回剩余的所有元素
var skipWhile = (from e in employees
select e).SkipWhile(r => r.Salary > 100000);
foreach (var item in skipWhile)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " Salary: " + item.Salary);
}
//******************************Output*******************************
//EmployeeName: Adolph Salary: 100000
//EmployeeName: Antony Salary: 320000
//EmployeeName: Asa Salary: 120000
//EmployeeName: Bernie Salary: 220000
//EmployeeName: Carl Salary: 100000
//EmployeeName: Duncan Salary: 250000
//EmployeeName: Aimee Salary: 80000
//EmployeeName: Cassie Salary: 350000
//*******************************************************************
8)Set操作符(Distinct、Union、Intersect、Except、Zip)
Distinct:從集合中刪掉重復的元素
//給所有員工的薪水排序,去掉重復的
var distinct = (from e in employees
orderby e.Salary
select e.Salary).Distinct();
foreach (var item in distinct)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//80000
//100000
//120000
//200000
//220000
//250000
//320000
//350000
//409989
//*******************************************************************
Union、Intersect、Except:並集、交集、差集
首先,我們準備兩個集合:員工姓名以A開頭和員工姓名以E結尾
var startWithA = (from e in employees
where e.EmployeeName.StartsWith("A")
select e).ToList();
var endWithE = (from e in employees
where e.EmployeeName.ToUpper().EndsWith("E")
select e).ToList();
以下分別取兩個集合的並集、交集、差集:
//查詢兩個集合的並集
var union = startWithA.Union(endWithE);
foreach (var item in union)
{
Console.WriteLine(item.EmployeeName);
}
//******************************Output*******************************
//Adolph
//Antony
//Asa
//Aimee
//Mike
//Bernie
//Cassie
//*******************************************************************
//--------------------------強勢分隔符--------------------------------
//查詢兩個集合的交集
var intersect = startWithA.Intersect(endWithE);
foreach (var item in intersect)
{
Console.WriteLine(item.EmployeeName);
}
//******************************Output*******************************
//Aimee
//*******************************************************************
//--------------------------強勢分隔符--------------------------------
//查詢兩個集合的差集
var except = startWithA.Except(endWithE);
foreach (var item in except)
{
Console.WriteLine(item.EmployeeName);
}
//******************************Output*******************************
//Adolph
//Antony
//Asa
//*******************************************************************
Zip:把兩個集合中對應的項目合並起來,在到大較小集合的末尾時停止
//把兩個集合中對應的項的姓名合並起來
var zip = startWithA.Zip(endWithE, (first, second) => first.EmployeeName + "+" + second.EmployeeName);
foreach (var item in zip)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//Adolph+Mike
//Antony+Bernie
//Asa+Aimee
//Aimee+Cassie
//*******************************************************************
9)元素操作符(First、FirstOrDefault、Last、LastOrDefault、ElementAt、ElementAtOrDefault、Single、SingleOrDefault)
First:返回第一個滿足條件的元素;若不存在,則引發異常。
FirstOrDefault:返回第一個滿足條件的元素;若不存在,則返回默認值。
//查詢年齡大於30歲的第一位員工的姓名
var first = (from e in employees
orderby e.Age
select e).First(r => r.Age > 30);
Console.WriteLine(first.EmployeeName);
//******************************Output*******************************
//Bernie
//*******************************************************************
假設需查詢年齡大於50歲的第一位員工的姓名,我們將上述代碼中年齡修改為50
var first = (from e in employees
orderby e.Age
select e).First(r => r.Age > 50);
Console.WriteLine(first.EmployeeName);
執行後發現異常
此時使用FirstOrDefault操作符:
//查詢年齡大於50歲的第一位員工的姓名,若不存在,則返回N/A
var firstOrDefault = (from e in employees
orderby e.Age
select e).FirstOrDefault(r => r.Age > 50);
Console.WriteLine(firstOrDefault == null ? "N/A" : firstOrDefault.EmployeeName);
//******************************Output*******************************
//N/A
//*******************************************************************
Last:返回最後一個滿足條件的元素;若不存在,則引發異常。
LastOrDefault:返回最後一個滿足條件的元素;若不存在,則返回默認值。
ElementAt:返回指定索引位置的元素;若不存在,則引發異常。
ElementAtOrDefault:返回指定索引位置的元素;若不存在,則返回默認值。
Single:只返回一個滿足條件的元素;若不存在或多個元素都滿足條件,則引發異常。
SingleOrDefault:只返回一個滿足條件的元素;若不存在或多個元素都滿足條件,則返回默認值。
10)聚合操作符(Count、Sum、Min、Max、Average、Aggregate)
Count:返回集合中的項數
//查找有一個以上愛好的員工的姓名、愛好的數量及部門
var count = from e in employees
let numberHobby = e.Hobby.Count()
where numberHobby > 1
select new
{
e.EmployeeName,
numberHobby,
e.Department
};
foreach (var item in count)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " NumberHobby: " + item.numberHobby + " Department: " + item.Department);
}
//******************************Output*******************************
//EmployeeName: Mike NumberHobby: 2 Department: IT
//EmployeeName: Adolph NumberHobby: 3 Department: IT
//EmployeeName: Antony NumberHobby: 2 Department: FD
//EmployeeName: Carl NumberHobby: 2 Department: QC
//EmployeeName: Aimee NumberHobby: 2 Department: HR
//*******************************************************************
Sum:計算所有值的總和
Min、Max、Average:最小值、最大值、平均值
//計算所有員工薪水的總和
var sum = (from e in employees
select e.Salary).Sum/*Min、Max、Average*/();
Console.WriteLine(sum.ToString("N0"));
//******************************Output*******************************
//2,149,989
//*******************************************************************
Aggregate:對序列進行累加
//初始值為50000000,依次累加所有員工的薪水
var aggregate = (from e in employees
select e.Salary).Aggregate(5000000, (x, y) => x + y, r => r * 2);
Console.WriteLine(aggregate.ToString("N0"));
//******************************Output*******************************
//14,299,978
//*******************************************************************
說明:Aggregate擴展方法的第一個參數為初始值。第二個參數是一個表達式,用來對每個元素進行計算(第一個參數是累加變量,第二個參數是當前值)。第三個參數是一個表達式,用來對最終結果進行計算。
11)轉換操作符(ToArray、AsEnumerable、ToList、ToDictionary、Cast<TResult>)
使用轉換操作符會立即執行查詢,將查詢結果放在數組、列表、字典中。
//將年齡大於30歲的元素放入list中再循環輸出。
List<Employee> employeeList = (from e in employees
where e.Age > 30
select e).ToList();
foreach (var item in employeeList)
{
Console.WriteLine("EmployeeName: " + item.EmployeeName + " Age:" + item.Age);
}
//******************************Output*******************************
//EmployeeName: Mike Age:32
//EmployeeName: Jack Age:38
//EmployeeName: Bernie Age:31
//EmployeeName: Cassie Age:31
//*******************************************************************
12)生成操作符(Empty、Range、Repeat)
生成操作符不是擴展方法,而是返回序列的靜態方法。在LINQ to Objects中,這些方法可用於Enumerable類。
Empty:生成空集合
//生成一個int類型的空序列
var empty = Enumerable.Empty<int>();
Console.WriteLine(empty.Count());
//******************************Output*******************************
//0
//*******************************************************************
Range:生成一系列數字的集合
//生成一個從1開始,10個元素的序列
var range = Enumerable.Range(1, 10);
foreach (var item in range)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//1
//2
//3
//4
//5
//6
//7
//8
//9
//10
//*******************************************************************
Repeat:返回始終重復一個值的集合
//生成一個10個元素,每個元素都是5的序列
var repeat = Enumerable.Repeat(5, 10);
foreach (var item in repeat)
{
Console.WriteLine(item);
}
//******************************Output*******************************
//5
//5
//5
//5
//5
//5
//5
//5
//5
//5
//*******************************************************************
本篇就此結束,主要介紹了LINQ的體系結構、基本語法以及LINQ to Obejcts中標準查詢操作符的使用方法。
示例代碼下載:https://github.com/Answer-Geng/LINQ
從LINQ開始之LINQ to Objects(上)