【.NET Core】Linq查詢運算符(二)
一、概述
查詢運算符是組成Linq模式的方法。這些方法中的大多數(shù)都作用于序列;其中序列指其類型實現(xiàn)IEnumberable<T>
接口或IQueryable<T>
接口的對象。標準查詢運算符提供包括篩選、投影、集合、排序等查詢功能。
查詢運算符包含兩組,一組作用于類型IEnumberable<T>
的對象,另一組作用于類型IQueryable<T>
的對象。
《Linq查詢運算符(一)》詳細介紹了篩選數(shù)據(jù)、投影運算、設置運算 、數(shù)據(jù)排序、限定符運算及數(shù)據(jù)分區(qū)本章將繼續(xù)介紹。
二、生成運算
2.1 DefaultIfEmpty
返回指定序列的元素;如果序列為空,則返回單一實例集合中的類型參數(shù)的默認值。
IList<int> list = new List<int>();
var lst= list.DefaultIfEmpty();
foreach (var item in lst)
{
Console.WriteLine(item);
}
輸出結果
0
2.2 Empty
初始化一個Empty空集合
var list=new List() 等于 var list = Enumerable.Empty();
var lst= Enumerable.Empty<int>();
foreach (var item in lst)
{
Console.WriteLine(item);
}
2.3 Range
Range()方法返回IEnumerable類型的集合,該集合具有指定數(shù)量的元素和從第一個元素開始的順序值。
var lst = Enumerable.Range(5, 2);
foreach (var item in lst)
{
Console.WriteLine(item);
}
執(zhí)行結果
5
6
2.4 Repeat
Repeat()方法使用指定數(shù)量的元素生成IEnumerable類型的集合,每個元素包含相同的指定值。
var lst = Enumerable.Repeat<double>(5, 2)
foreach (var item in lst)
{
Console.WriteLine(item);
}
執(zhí)行結果
5
5
三、相等運算
3.1 SequenceEqual
兩個序列,其相應元素相等且具有被視為相等的相同數(shù)量的元素
public class Person
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
IList<int> listA = new List<int>() { 1, 2, 3, 4 };
IList<int> listB = new List<int>() { 1, 2, 3, 4 };
IList<int> listC = new List<int>() { 2, 1, 3, 4 };
bool falg= Enumerable.SequenceEqual(listA, listB);
Console.WriteLine(falg);
bool falgC = Enumerable.SequenceEqual(listA, listC);
Console.WriteLine(falgC);
IList<Person> peopleA = new List<Person>() {
new Person { Id = 2, Code = "002", Name = "CAZ" },
new Person { Id = 2, Code = "002", Name = "CAZ" },
};
IList<Person> peopleB = new List<Person>() {
new Person { Id = 2, Code = "002", Name = "CAZ" },
new Person { Id = 2, Code = "002", Name = "CAZ" },
};
bool flagPersonA = Enumerable.SequenceEqual<Person>(peopleA, peopleB);
Console.WriteLine(flagPersonA);
bool flagPersonB = Enumerable.SequenceEqual<Person>(peopleA, peopleB, new StudentComparer());
Console.WriteLine(flagPersonB);
/// <summary>
/// 重寫比較接口
/// </summary>
public class StudentComparer : IEqualityComparer<Person>
{
public bool Equals(Person? x, Person? y)
{
if (x.Id == y.Id && x.Code.ToLower() == y.Code.ToLower())
return true;
return false;
}
public int GetHashCode([DisallowNull] Person obj)
{
return obj.GetHashCode();
}
}
四、元素運算
元素運算從序列中返回唯一,特定的元素。
4.1 ElementAt
返回集合中指定索引處的元素。
IList<Person> peopleA = new List<Person>() {
new Person { Id = 1, Code = "001", Name = "任峻" },
new Person { Id = 2, Code = "002", Name = "陳矯" },
new Person { Id = 3, Code = "003", Name = "丁儀" },
new Person { Id = 4, Code = "004", Name = "司馬朗" },
new Person { Id = 5, Code = "005", Name = "夏侯淵" },
};
Person person= peopleA.ElementAt(4);
Console.WriteLine($"Id={person.Id},Code={person.Code},Name={person.Name}");
執(zhí)行結果
Id=5,Code=005,Name=夏侯淵
4.2 ElementAtOrDefault
返回集合中指定索引處的元素;如果索引超出范圍,則返回默認值。
IList<Person> peopleA = new List<Person>() {
new Person { Id = 1, Code = "001", Name = "任峻" },
new Person { Id = 2, Code = "002", Name = "陳矯" },
new Person { Id = 3, Code = "003", Name = "丁儀" },
new Person { Id = 4, Code = "004", Name = "司馬朗" },
new Person { Id = 5, Code = "005", Name = "夏侯淵" },
};
Person person= peopleA.ElementAtOrDefault<Person>(5);
Console.WriteLine($"Id={person?.Id},Code={person?.Code},Name={person?.Name}");
執(zhí)行結果
Id=,Code=,Name=
4.1 First
返回集合的第一個元素或滿足條件的第一個元素。
IList<Person> peopleA = new List<Person>() {
new Person { Id = 1, Code = "001", Name = "任峻" },
new Person { Id = 2, Code = "002", Name = "陳矯" },
new Person { Id = 3, Code = "003", Name = "丁儀" },
new Person { Id = 4, Code = "004", Name = "司馬朗" },
new Person { Id = 5, Code = "005", Name = "夏侯淵" },
};
Person person= peopleA.First();
Console.WriteLine($"Id={person?.Id},Code={person?.Code},Name={person?.Name}");
執(zhí)行結果
Id=1,Code=001,Name=任峻
4.2 FirstOrDefault
int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };
var nums = numbers.FirstOrDefault<int>(e=>e<1);
Console.WriteLine($"{ nums}");
執(zhí)行結果
0
4.3 Last
返回集合的最后一個元素或滿足條件的最后一個元素。
int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };
var nums = numbers.Last(e=>e<5);
Console.WriteLine($"{ nums}");
執(zhí)行結果
3
4.4 LastOrDefault
返回集合的最后一個元素或滿足條件的最后一個元素。 如果此類元素不存在,則返回默認值。
int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };
var nums = numbers.LastOrDefault(e=>e>11);
Console.WriteLine($"{ nums}");
執(zhí)行結果
0
4.5 Single
返回集合的唯一一個元素或滿足條件的唯一一個元素。如果沒有要返回的元素或要返回多個元素,則引發(fā)InvalidOperationException。
int[] numbers = new int[] { 100};
int result = numbers.Single();
Console.WriteLine(result);
執(zhí)行結果
100
4.6 SingleOrDefault
返回集合的唯一一個元素或滿足條件的唯一一個元素。如果沒有要返回的元素或要返回多個元素,則引發(fā)InvalidOperationException。
int[] numbers = new int[] { 100};
int result = numbers.SingleOrDefault();
Console.WriteLine(result);
執(zhí)行結果
100
五、轉(zhuǎn)換數(shù)據(jù)類型
轉(zhuǎn)換數(shù)據(jù)類型可以通過轉(zhuǎn)換方法更改輸入對象的類型。名稱以“As”開頭的轉(zhuǎn)換方法可更改源集合的靜態(tài)類型但不枚舉(延遲加載)此源集合。名稱以“To”開頭的方法可枚舉(即時加載)源集合并將項放入相應的集合類型。
5.1 AsEnumerable
所有實現(xiàn)了IEnumerable接口的類型都可以調(diào)用此方法來獲取一個IEnumerable集合。此方法一般僅用于實現(xiàn)類中的方法與IEnumerable接口方法重名時。
var products = db.Product.AsEnumerable()
.Select(p => new {p.Id, p.Name, p.CreateTime.Date});
在迭代時遇見AsEnumerable()會先進行Sql查詢,對已查出來的結果當然能進行Linq to object操作。
5.2 AsQueryable
AsQueryable將一個序列向下轉(zhuǎn)換 一個IQueryable,它生成了一個本地查詢的IQueryable包裝。IQueryable實現(xiàn)了IEnumerable接口。但IEnumerable換成IQueryable后速度提高很多。
var query = (from item in context.Users.AsQueryable() where item.id > 10
select item.id).ToList();
5.3 AsEnumerable和AsQueryable
- AsEnumerable()是延遲執(zhí)行的,實際上什么都沒有發(fā)生,當真正使用對象的時候(例如調(diào)用:First, Single, ToList…的時候)才執(zhí)行。
- AsEnumerable將一個序列向上轉(zhuǎn)換為一個IEnumerable, 強制將Enumerable類下面的查詢操作符綁定到后續(xù)的子查詢當中。
- AsQueryable將一個序列向下轉(zhuǎn)換為一個IQueryable, 它生成了一個本地查詢的IQueryable包裝。
- AsEnumerable()延遲執(zhí)行,不會立即執(zhí)行。當你調(diào)用.AsEnumerable()的時候,實際上什么都沒有發(fā)生。
- ToList()立即執(zhí)行。
- 當你需要操作結果的時候,用.ToList(),否則,如果僅僅是用來查詢不需要進一步使用結果集,并可以延遲執(zhí)行,就用.AsEnumerable()/IEnumerable /IQueryable。
- AsEnumerable()雖然延遲執(zhí)行,但還是訪問數(shù)據(jù)庫,而.ToList()直接取得結果放在內(nèi)存中。比如我們需要顯示兩個部門的員工時,部門可以先取出放置在List中,然后再依次取出各個部門的員工,這時訪問的效率要高一些,因為不需要每次都訪問數(shù)據(jù)庫去取出部門。
- IQueryable實現(xiàn)了IEnumberable接口。但IEnumerable 換成IQueryable后速度提高很多。
- IEnumerable跑的是Linq to Object,強制從數(shù)據(jù)庫中讀取所有數(shù)據(jù)到內(nèi)存先。
5.4 Cast
將集合中的元素轉(zhuǎn)換為指定類型。
DataRow row=dt.Rows.Cast<DataRow>().Single();
5.5 OfType
根據(jù)其轉(zhuǎn)換為指定類型的能力篩選值。
List<object> objList = new List<object> {
new { ID = 1, Name = "阿里" },
new { ID = 2, Name = "百度" },
new Person() { Id=1, Name = "馬云", Code="001" }
};
var p = objList.OfType<Person>().ToList();
foreach (var item in p)
{
Console.WriteLine(item.Name);
}
5.6 ToArray
將結合轉(zhuǎn)換為數(shù)組。此方法強制執(zhí)行查詢。
IList<string> list = new List<string>() { "A", "B", "C" };
string[] arr= list.ToArray();
5.7 ToDictionary
根據(jù)鍵選擇器函數(shù)將元素放入Dictionary<TKey,TValue>
。此方法強制執(zhí)行查詢。
Person[] parameters = new Person[]
{
new Person() { Id = 1, Code = "052", Name = "正一郎" },
new Person() { Id = 2, Code = "028", Name = "清次郎" },
new Person() { Id = 3, Code = "020", Name = "誠三郎" },
new Person() { Id = 4, Code = "018", Name = "征史郎" },
};
Dictionary<int, Person> dictionary = parameters.ToDictionary(value => value.Id);
5.8 ToList
將集合轉(zhuǎn)換為List<T>
。此方法強制執(zhí)行查詢。文章來源:http://www.zghlxwxcb.cn/news/detail-753045.html
string[] strArr = { "1","2", "3" };
IList<string> strList = strArr.ToList();
5.9 ToLookup
根據(jù)鍵選擇器函數(shù)將元素放入Lookup<TKey,TElement>
(一對多字典)。此方法強制執(zhí)行查詢。該ToLookup()
是不可改變,一旦創(chuàng)建一個Lookup
,不能添加或刪除元素。文章來源地址http://www.zghlxwxcb.cn/news/detail-753045.html
IList<Person> values = new List<Person>()
{
new Person { Id=1,Name="0001"},
new Person { Id=2,Name="0002"},
new Person{ Id=3,Name="0003"},
new Person{ Id=4,Name="0004"},
};
var list = values.ToLookup(e => e.Id);
foreach (var item in list)
{
Console.WriteLine(item.Key);
}
到了這里,關于【.NET Core】Linq查詢運算符(二)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!