C#使用LINQ中Enumerable類方法的延遲與立即執(zhí)行的控制
延時(shí)執(zhí)行的Enumerable類方法
LINQ標(biāo)準(zhǔn)查詢運(yùn)算法是依靠一組擴(kuò)展方法來實(shí)現(xiàn)的。而這些擴(kuò)展方法分別在System.Linq.Enumerable和System.Linq.Queryable這連個靜態(tài)類中定義。
Enumerable的擴(kuò)展方法采用線性流程,每個運(yùn)算法會被線性執(zhí)行。這種執(zhí)行方法如果操作類似關(guān)系型數(shù)據(jù)庫數(shù)據(jù)源,效率會非常低下,所以Queryable重新定義這些擴(kuò)展方法,把LINQ表達(dá)式拆解為表達(dá)式樹,提供程序就可以根據(jù)表達(dá)式樹生成關(guān)系型數(shù)據(jù)庫的查詢語句,即SQL命令,然后進(jìn)行相關(guān)操作。
每個查詢運(yùn)算符的執(zhí)行行為不同,大致分為立即執(zhí)行和延時(shí)執(zhí)行。延時(shí)執(zhí)行的運(yùn)算符將在枚舉元素的時(shí)候被執(zhí)行。
Enumerable類位于程序集System.Core.dll中,System.Linq命名空間下,并且直接集成自System.Object,存在于3.5及以上的.NET框架中。Enumerable是靜態(tài)類,不能實(shí)例化和被繼承,其成員只有一組靜態(tài)和擴(kuò)展方法。
LINQ不僅能夠查詢實(shí)現(xiàn)IEnumerable<T>或IQueryable<T>的類型,也能查詢實(shí)現(xiàn)IEnumerable接口的類型。
理解LINQ首先必須理解擴(kuò)展方法
msdn是這樣規(guī)定擴(kuò)展方法的:“擴(kuò)展方法被定義為靜態(tài)方法,但它們是通過實(shí)例方法語法進(jìn)行調(diào)用的。 它們的第一個參數(shù)指定該方法作用于哪個類型,并且該參數(shù)以 this 修飾符為前綴。”
下面給個擴(kuò)展方法的例子如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 擴(kuò)展方法
{
/// <summary>
/// 為string類型定義一個擴(kuò)展方法
/// </summary>
static class Helper
{
public static string MyExtenMethod(this string s)
{
return s.Substring(0, 2);
}
}
class Program
{
static void Main(string[] args)
{
string s = "擴(kuò)展方法示例";
Console.WriteLine(s.MyExtenMethod());//調(diào)用
Console.ReadKey(false);
}
}
}
程序的運(yùn)行結(jié)果如下:
為了方便理解和記憶,將常用的延時(shí)執(zhí)行的Enumerable類方法成員分了下組,具體如下:
1.Take用于從一個序列的開頭返回指定數(shù)量的元素
2.TakeWhile 用于獲取指定序列從頭開始符合條件的元素,直到遇到不符合條件的元素為止
3.Skip跳過序列中指定數(shù)量的元素
4.SkipWhile 用于跳過序列總滿足條件的元素,然會返回剩下的元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 延時(shí)執(zhí)行的Enumerable類方法
{
class Program
{
static void Main(string[] args)
{
string[] names = { "DebugLZQ","DebugMan","Sarah","Jerry","Tom","Linda","M&M","Jeffery"};
//1.Take用于從一個序列的開頭返回指定數(shù)量的元素
//
//a.在數(shù)組上直接使用Take方法
foreach (string name in names.Take(3))
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("-----");
//b.在LINQ返回的IEnumerable<T>序列上使用Take方法
var query = from string name in names
where name.Length <=3
select name;
foreach (string name in query.Take(1))
{
Console.Write("{0} ",name);
}
Console.WriteLine();
Console.WriteLine("----------------------------");
Console.ReadKey(false);
//2.TakeWhile 用于獲取指定序列從頭開始符合條件的元素,直到遇到不符合條件的元素為止
//
var takenames = names.TakeWhile(n => n.Length>4);
var takenames2 = names.TakeWhile((n,i)=>n.Length<10&&i<3);
foreach (string name in takenames)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("-----");
foreach (string name in takenames2)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("----------------------------");
Console.ReadKey(false);
//3.Skip跳過序列中指定數(shù)量的元素
//
foreach (string name in names.Skip(5))
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("-----");
var query_skip = (from name in names
where name.Length >= 3
select name).Skip(2);
foreach (string name in query_skip.Skip(2) )
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("----------------------------");
Console.ReadKey(false);
//4.SkipWhile 用于跳過序列總滿足條件的元素,然會返回剩下的元素
//跳過名字長度大于3的
var takenames_SkipWhile = names.SkipWhile(n => n.Length >3);
foreach (string name in takenames_SkipWhile)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("-----");
var takenames_SkipWhile2 = names.SkipWhile((n,i)=>n.Length>3&&i>2);
foreach (string name in takenames_SkipWhile2)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("----------------------------");
Console.ReadKey(false);
//小結(jié)Take、Skip獲得第N到第M個元素
var names_TakeAndSkip = names.Skip(5).Take(3);
var names_TakeAndSkip2 = (from name in names
select name).Skip(5).Take(3);
foreach (string name in names_TakeAndSkip)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("-----");
foreach (string name in names_TakeAndSkip2)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
Console.WriteLine("----------------------------");
Console.ReadKey(false);
}
}
}
程序中有詳細(xì)的注釋不再多做說明,程序運(yùn)行結(jié)果如下:
5.Reverse用于翻轉(zhuǎn)序列中的元素的順序
6.Distinct過濾掉重復(fù)的元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reverse_Distinct等
{
class Program
{
static void Main(string[] args)
{
string[] names = { "DebugLZQ", "Jerry", "Sarah", "Jerry", "Tom", "Linda", "M&M", "Jeffery" };
//5.Reverse用于翻轉(zhuǎn)序列中的元素的順序
string str = "反轉(zhuǎn)字符串";
var strre = str.ToCharArray().Reverse();
var takenames = names.Reverse();
foreach (var c in strre)
{
Console.Write(c);
}
Console.WriteLine();
Console.WriteLine("-----");
foreach (var c in takenames )
{
Console.WriteLine(c);
}
Console.WriteLine("----------------------------");
Console.ReadKey(false);
//6.Distinct 過濾掉重復(fù)的元素
var takenames_Distinct = names.Distinct();
foreach (var c in takenames_Distinct)
{
Console.WriteLine(c);
}
Console.WriteLine("----------------------------");
Console.ReadKey(false);
}
}
}
程序的運(yùn)行結(jié)果如下:
7.Union用于合并兩個序列,并去掉重復(fù)項(xiàng)
8.Concat用于連接兩個序列,不會去掉重復(fù)項(xiàng)
9.Intersect用于獲得連個序列的交集
10.Except用于獲得兩個結(jié)合的差集
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Union_Concat_Intersect_Except
{
/// <summary>
/// DebugLZQ
/// http://www.cnblogs.com/DebugLZQ
/// </summary>
class Program
{
static void Main(string[] args)
{
string[] names1 = { "DebugLZQ", "Jerry", "Sarah", "Jerry", "Tom", "Linda", "M&M", "Jeffery" };
string[] names2 = { "DebugLZQ", "Jerry", "Sarah" };
//7.Union用于合并兩個序列,并去掉重復(fù)項(xiàng)
var names_Union = names1.Union(names2);
//8.Concat用于連接兩個序列,不會去掉重復(fù)項(xiàng)
var names_Concat = names1.Concat(names2);
//9.Intersect用于獲得連個序列的交集
var names_Intersect = names1.Intersect(names2);
//10.Except用于獲得兩個結(jié)合的差集
var names_Except = names1.Except(names2);
foreach (string name in names_Union)
{
Console.WriteLine(name);
}
Console.WriteLine("-----");
Console.ReadKey(false);
foreach (string name in names_Concat)
{
Console.WriteLine(name);
}
Console.WriteLine("-----");
Console.ReadKey(false);
foreach (string name in names_Intersect)
{
Console.WriteLine(name);
}
Console.WriteLine("-----");
Console.ReadKey(false);
foreach (string name in names_Except)
{
Console.WriteLine(name);
}
Console.WriteLine("-----");
Console.ReadKey(false);
}
}
}
程序的運(yùn)行結(jié)果如下:
11.Range 用于生成指定范圍內(nèi)的“整數(shù)”序列
12.Repeat用于生成指定數(shù)量的重復(fù)元素
13.Empty 用于獲得一個指定類型的空序列
14.DefaultIfEmpty 用于獲得序列,如果為空,則添加一個默認(rèn)類型元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Range_Empty_DefalultIfEmpty
{
/// <summary>
/// DebugLZQ
/// http://www.cnblogs.com/DebugLZQ
/// </summary>
class Program
{
static void Main(string[] args)
{
//11.Range 用于生成指定范圍內(nèi)的“整數(shù)”序列
var num2 = Enumerable.Range(10, 15);
//12.Repeat用于生成指定數(shù)量的重復(fù)元素
var guest = new {Name="橙子",Age=25 };
var Guests = Enumerable.Repeat(guest, 5);
//13.Empty 用于獲得一個指定類型的空序列
var empty = Enumerable.Empty<string>();
//14.DefaultIfEmpty 用于獲得序列,如果為空,則添加一個默認(rèn)類型元素
//a
var intempty = Enumerable.Empty<int>();
Console.WriteLine(intempty.Count());
Console.WriteLine("-----------");
foreach (var n in intempty)
{
Console.WriteLine(n);
}
Console.WriteLine("-----------");
Console.WriteLine(intempty.DefaultIfEmpty().Count());
Console.WriteLine("-----------");
foreach (var n in intempty.DefaultIfEmpty())
{
Console.WriteLine(n);
}
Console.WriteLine("--------------------------");
Console.ReadKey(false);
//b
string[] names = { "DebugLZQ", "DebugMan", "Sarah", "Jerry", "Tom", "Linda", "M&M", "Jeffery" };
var query = from name in names
where name == "LBJ"
select name;
Console.WriteLine(query.Count());
Console.WriteLine(query.DefaultIfEmpty().Count());//默認(rèn)為null
foreach (var n in query.DefaultIfEmpty())
{
Console.WriteLine(n);
}
Console.WriteLine("---------------");
Console.ReadKey(false);
//c指定一個默認(rèn)值
foreach (var n in intempty.DefaultIfEmpty(100))
{
Console.WriteLine(n);
}
Console.WriteLine("--------------------------");
Console.ReadKey(false);
foreach (var n in query.DefaultIfEmpty("James"))
{
Console.WriteLine(n);
}
Console.ReadKey(false);
}
}
}
程序的運(yùn)行結(jié)果如下:
15.OfType篩選指定類型的元素
16.Cast類型轉(zhuǎn)換
17.AsEnumerable有些數(shù)據(jù)源類型不支持Enumerable的部分查詢關(guān)鍵字,需要轉(zhuǎn)換下,譬如IQueryable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Cast_OfType_AsEnumerable
{
/// <summary>
/// DebugLZQ
/// http://www.cnblogs.com/DebugLZQ
/// </summary>
class Program
{
static void Main(string[] args)
{
ArrayList names = new ArrayList();
names.Add("DebugLZQ");
names.Add("Jerry");
names.Add(100);
names.Add(new {Name="LZQ",Age=26});
names.Add(new Stack());
//15.OfType篩選指定類型的元素
var takenames = names.OfType<string>();
//16.Cast類型轉(zhuǎn)換
var takenames2 = names.OfType<string>().Cast<string>();
//17.AsEnumerable
var takenames3 = takenames2.AsEnumerable();
foreach (var name in takenames3)
{
Console.Write("{0} ",name);
}
Console.ReadKey(false);
}
}
}
程序運(yùn)行結(jié)果如下:
延時(shí)執(zhí)行,顧名思義就是不是立即執(zhí)行,即不是在查詢語句定義的時(shí)候執(zhí)行,而是在處理結(jié)果集(如遍歷)的時(shí)候執(zhí)行,在Enumerable類方法成員中,除了本節(jié)總結(jié)的這常用的17個外,前面博文---LINQ基本子句 中總結(jié)的8個基本子句也都是延時(shí)執(zhí)行的。注意延時(shí)執(zhí)行的查詢程序的執(zhí)行流程。
立即執(zhí)行的Enumerable類方法
下面我們再來總結(jié)常用的立即執(zhí)行的Enumerable類方法和它們的常用用法。同樣,為了便于理解和記憶,進(jìn)行一下分組:
1.ToArray序列轉(zhuǎn)換成數(shù)組
2.ToList序列轉(zhuǎn)換成List<T>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 立即執(zhí)行的Enumerable類方法成員
{
class Program
{
static void Main(string[] args)
{
//1.ToArray序列轉(zhuǎn)換成數(shù)組
List<string> names =new List<string> { "DebugLZQ","Sarah","Jerry","Jeffrey","M&M"};
string[] takenames = names.ToArray();
string[] takenames2 = (from name in names
where name.IndexOf("Je")>-1
select name).ToArray();
//2.ToList序列轉(zhuǎn)換成List<T>
string[] namesA = { "DebugLZQ", "Sarah", "Jerry", "Jeffrey", "M&M" };
List<string> takenames_ToList = namesA.ToList();
List<string> takenames_ToList2 = (from name in namesA select name).ToList();
//
}
}
}
程序結(jié)果顯而易見,所以沒有寫輸出語句;
3.ToDictionary把序列轉(zhuǎn)換為泛型Dictionary<TKey,TValue>
4.ToLookup用于將序列轉(zhuǎn)換為泛型Lookup<TKey,TValue>
Dictionary和Lookup是非常近似的一對類型,都通過“鍵”訪問相關(guān)的元素,不同的是Dictionary的Key和Value是一一對應(yīng)關(guān)系,Lookup的Key和Value是一對多關(guān)系,Lookup沒有公共構(gòu)造函數(shù),時(shí)能用ToLookup構(gòu)建,創(chuàng)建后也不能刪除Lookup中的元素。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToDictionary
{
/// <summary>
/// 3.ToDictionary把序列轉(zhuǎn)換為泛型Dictionary<TKey,TValue>
/// </summary>
class Program
{
static void Main(string[] args)
{
List<GuestInfo> gList = new List<GuestInfo>()
{
new GuestInfo(){Name="Jeffrey", Age=33,Tel="136********"},
new GuestInfo(){ Name="DebugLZQ", Age=25,Tel="187********"},
new GuestInfo(){Name="Sarah", Age=24,Tel="159********"},
new GuestInfo(){Name="Jerry", Age=33,Tel="135********"},
new GuestInfo(){Name="Smith", Age=33,Tel="139********"}
};
//ToDictionary把序列轉(zhuǎn)換為泛型Dictionary
//ToDictionary重載了4個方法
//a.用Name作為Dictionary的“鍵”,guest為“value”
Dictionary<string, GuestInfo> dictionary1 = gList.ToDictionary(guest => guest.Name);
foreach (var s in dictionary1 )
{
Console.WriteLine("鍵值{0}:{1} {2} {3}",s.Key,s.Value.Name,s.Value.Age,s.Value.Tel );
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
//b.自定義比較器
Dictionary<string,GuestInfo> dictionary2=gList.ToDictionary(guest=>guest.Name,new MyEqualityComparer<string>());
foreach (var s in dictionary2)
{
Console.WriteLine("鍵值{0}:{1} {2} {3}", s.Key, s.Value.Name, s.Value.Age, s.Value.Tel);
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
//c.用Name作為Dictionary的“鍵”,Tel屬性為"value"
Dictionary<string, string> dictionary3 = gList.ToDictionary(guest=>guest.Name,g=>g.Tel);
foreach (var s in dictionary3)
{
Console.WriteLine("鍵值{0}:{1}", s.Key, s.Value);
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
//d.自定義比較器
Dictionary<string, string> dictionary4 = gList.ToDictionary(guest=>guest.Name,g=>g.Tel,new MyEqualityComparer<string>());
foreach (var s in dictionary4)
{
Console.WriteLine("鍵值{0}:{1}", s.Key, s.Value);
}
Console.WriteLine("------------------------------------------------------");
Console.ReadKey();
///////////////
///4.ToLookup用于將序列轉(zhuǎn)換為泛型Lookup<TKey,TValue>。
///Dictionary和Lookup是非常近似的一對類型,都通過“鍵”訪問相關(guān)的元素,不同的是Dictionary的Key和Value是一一對應(yīng)關(guān)系
///Lookup的Key和Value是一對多關(guān)系
///Lookup沒有公共構(gòu)造函數(shù),時(shí)能用ToLookup構(gòu)建,創(chuàng)建后也不能刪除Lookup中的元素。
///該方法也有4個原型,和上面的ToDictionary極像
///
//a. Name的第一個字符(字符串)作key
ILookup<string, GuestInfo> lookup1 = gList.ToLookup(guest => guest.Name.Substring(0, 1));
foreach (var k in lookup1)
{
Console.WriteLine(k.Key);//鍵值
foreach (var v in k)
{
Console.Write("{0},{1},{2}",v.Name,v.Age,v.Tel );
}
Console.WriteLine();
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
//b自定義比較器
ILookup<string, GuestInfo> lookup2 = gList.ToLookup(guest => guest.Name.Substring(0, 1), new MyEqualityComparer<string>());
foreach (var k in lookup2)
{
Console.WriteLine(k.Key);//鍵值
foreach (var v in k)
{
Console.Write("{0},{1},{2}", v.Name, v.Age, v.Tel);
}
Console.WriteLine();
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
//c
ILookup<string, string> lookup3 = gList.ToLookup(guest=>guest.Name.Substring(0,1),g=>g.Name );
foreach (var k in lookup3)
{
Console.WriteLine(k.Key);//鍵值
foreach (var v in k)
{
Console.Write("{0} ", v);
}
Console.WriteLine();
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
//d自定義比較器
ILookup<string, string> lookup4 = gList.ToLookup(guest=>guest.Name.Substring(0,1),g=>g.Name,new MyEqualityComparer<string>());
foreach (var k in lookup4)
{
Console.WriteLine(k.Key);//鍵值
foreach (var v in k)
{
Console.Write("{0} ", v);
}
Console.WriteLine();
}
Console.WriteLine("--------------------------------");
Console.ReadKey();
}
}
}
程序運(yùn)行結(jié)果如下:
沒有顯示完全,后面一組輸出和上面最后一組相同(只是使用了自定義的比較器)。
5.SequenceEqual 比較兩個序列是否相等
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SequenceEqual
{
/// <summary>
///
/// </summary>
class Program
{
static void Main(string[] args)
{
//5.SequenceEqual 比較兩個序列是否相等
//a比較兩個序列
string[] names1 ={ "DebugLZQ","Sarah","Jerry","Jeffrey","M&M"};
List<string> names2 = new List<string> { "DebugLZQ", "Sarah", "Jerry", "Jeffrey", "M&M" };
bool equalornot = names1.SequenceEqual(names2);
bool equalornot2 = names1.Skip(3).Take(2).SequenceEqual(names2.Take(3).SkipWhile(n=>n.Length==3));
Console.WriteLine("{0},{1}",equalornot,equalornot2 );
Console.WriteLine("----------------------------");
Console.ReadKey();
//b自定義比較器
bool equalornot3 = names1.SequenceEqual(names2, new MyEqualityComparer<string>(names2.ToArray()));
Console.WriteLine("{0}",equalornot3);
Console.ReadKey();
}
}
}
自定義的比較器如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SequenceEqual
{
//DebugLZQ提示:
//如不知道具體的接口實(shí)現(xiàn)
//可以用vs提供的自動實(shí)現(xiàn)接口功能實(shí)現(xiàn)這個接口
class MyEqualityComparer<T> : IEqualityComparer<T>
{
private string[] sec;
public MyEqualityComparer(string[] s)
{
sec = s;
}
#region IEqualityComparer<T> 成員
public bool Equals(T x, T y)
{
string temp = x as string;
if (x != null)
{
return sec.Contains(temp);
}
return false;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
#endregion
}
}
可以使用VS自動實(shí)現(xiàn)接口的智能提示,完成接口的實(shí)現(xiàn)。
接口的實(shí)現(xiàn)方式有“實(shí)現(xiàn)接口”和“顯式實(shí)現(xiàn)接口”之分,上面這種實(shí)現(xiàn)方式即“顯示接口”方式,“顯示實(shí)現(xiàn)接口”最顯著的特征是實(shí)現(xiàn)的接口方法加了個完全限定名,這樣顯式實(shí)現(xiàn)之后,無法通過具體的類名來訪問接口方法,只能通過接口名來訪問,這樣可以隱藏類的復(fù)雜性。
程序運(yùn)行結(jié)果如下:
6.First 返回序列第一個滿足條件元素
7.FirstOrDefault 返回序列第一個滿足條件元素,如果沒有找到則返回默認(rèn)值
8.Last
9.LastOrDefault
10.Single返回序列中唯一的元素,如果序列中包含多個元素,會引發(fā)運(yùn)行錯誤!
11.SingleOrDefault 找出序列中滿足一定條件的元素,如果序列為空則返回默認(rèn)值, 如果序列中包含多個多個元素會引發(fā)運(yùn)行錯誤?。?/p>
12.ElementAt 獲得指定索引處的元素
13.ElementAtOrDefault 獲得指定索引處的元素,如果超出索引,則返回元素類型的默認(rèn)值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace First_FirstOrDefault_Last_LastOrDefault_ElementAt_ElementAtOrDefaul
{
class Program
{
static void Main(string[] args)
{
//6.First
string[] names = { "DebugLZQ", "Sarah", "Jerry", "Jeffrey", "M&M" };
var item = names.First();
var item2 = names.First(n => n == "Sarah");
Console.WriteLine("{0},{1}",item,item2 );
Console.ReadKey();
//7.FirstOrDefault
var item3 = names.FirstOrDefault();
var item4 = names.FirstOrDefault(n => n == "Sarah");
Console.WriteLine("{0},{1}", item3, item4);
Console.ReadKey();
//8.Last
var item5 = names.Last();
var item6 = names.LastOrDefault(n => n == "Sarah");
Console.WriteLine("{0},{1}", item5, item6);
Console.ReadKey();
//9LastOrDefault
var item7 = names.LastOrDefault();
var item8 = names.LastOrDefault(n => n == "Sarah");
Console.WriteLine("{0},{1}", item7, item8);
Console.ReadKey();
//10.Single返回序列中唯一的元素,如果序列中包含多個元素,會引發(fā)運(yùn)行錯誤!
try
{
var item9 = names.Single();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
//
var item10 = names.Single(n => n == "Sarah");
Console.WriteLine("{0}",item10 );
Console.ReadKey();
//11.SingleOrDefault 找出序列中滿足一定條件的元素,如果序列為空則返回默認(rèn)值, 如果序列中包含多個多個元素會引發(fā)運(yùn)行錯誤?。?
try
{
var item11 = Enumerable.Empty<string>().SingleOrDefault();
Console.WriteLine("{0}",item11);//不報(bào)錯,如果序列為空就返回默認(rèn)值
}
catch (Exception ex)
{
Console.WriteLine(ex.Message );
}
try
{
var item12 = names.SingleOrDefault();
Console.WriteLine("{0}", item12);//報(bào)錯,序列包含多行錯誤
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var item13 = Enumerable.Empty<string>().DefaultIfEmpty("DebugLZQ").SingleOrDefault();
Console.WriteLine("{0}", item13);
var item14 = names.SingleOrDefault(n => n == "xxx");
Console.WriteLine("{0}", item14);
Console.ReadKey();
//12ElementAt 獲得指定索引處的元素
var item15 = names.ElementAt(3);
Console.WriteLine("{0}", item15);
Console.ReadKey();
//13ElementAtOrDefault 獲得指定索引處的元素,如果超出索引,則返回元素類型的默認(rèn)值
var item16 = names.ElementAtOrDefault(3);
var item17 = names.ElementAtOrDefault(100);
Console.WriteLine("{0},{1}",item16,item17);
Console.ReadKey();
}
}
}
程序運(yùn)行結(jié)果如下:
14.All序列中的所有元素是否都滿足條件
15.Any序列中的元素是否存在或滿足條件
16.Contains確定元素是否在序列中
17.Count序列包含元素的數(shù)量
18.LongCount獲取一個Int64類型的元素?cái)?shù)量
19.Aggregate將序列元素進(jìn)行累加
20.Sum序列之和
21.Average序列平均值
22.Min序列的最小值
23.Max序列的最大值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace All_Any_Count_LongCount_Aggregate_SumAverage_Min_Max
{
class Program
{
static void Main(string[] args)
{
string[] names = { "DebugLZQ", "Sarah", "Jerry", "Jeffrey", "M&M" };
//14All序列中的所有元素是否都滿足條件
bool b1 = names.All(s=>s.GetTypeCode()==TypeCode.String );
bool b2 = names.All(s=>s.IndexOf("S")>-1);
Console.WriteLine("{0},{1}",b1,b2);
Console.ReadKey();
Console.WriteLine("----------------------");
//15Any序列中的元素是否存在或滿足條件
bool p1 = names.Any();
bool p2 = names.Any(s => s.IndexOf("S")>-1);
Console.WriteLine("{0},{1}", p1, p2);
Console.ReadKey();
Console.WriteLine("----------------------");
//16Contains確定元素是否在序列中
//a
bool q1 = names.Contains("MM");
//b自定義比較函數(shù)
bool q2 = names.Contains("MM", new MyEqualityComparer<string>());
Console.WriteLine("{0},{1}", q1, q2);
Console.ReadKey();
Console.WriteLine("----------------------");
//17Count序列包含元素的數(shù)量
int i1 = names.Count();
int i2 = names.Count(n => n.Length == 5);
Console.WriteLine("{0},{1}", i1, i2);
Console.ReadKey();
Console.WriteLine("----------------------");
//18LongCount獲取一個Int64類型的元素?cái)?shù)量
long j1 = names.LongCount();
long j2 = names.LongCount(n => n.Length == 5);
Console.WriteLine("{0},{1}",j1, j2);
Console.ReadKey();
Console.WriteLine("----------------------");
//19Aggregate將序列元素進(jìn)行累加
int[] nums = { 10,20,30,40,50};
int a1 = nums.Aggregate((n1,n2)=>n1+n2);//150
int a2 = nums.Aggregate(50,(n1,n2)=>n1+n2);//200
Console.WriteLine("{0},{1}", a1, a2);
string s1 = names.Aggregate((name1,name2)=>string.Format("{0}、{1}",name1,name2));
string s2= names.Aggregate("The result is ",(name1, name2) => string.Format("{0}、{1}", name1, name2));
Console.WriteLine("{0}", s1);
Console.WriteLine("{0}", s2);
Console.ReadKey();
Console.WriteLine("----------------------");
//20Sum序列之和
int sum = nums.Sum();
//21Average序列平均值
double avg = nums.Average();
//22Min序列的最小值
int min = nums.Min();
//23Max序列的最大值
int max=nums.Max();
Console.WriteLine("{0},{1},{2},{3}", sum, avg,min,max);
Console.ReadKey();
}
}
}
程序運(yùn)行結(jié)果如下:
上一篇:區(qū)分WCF與WebService的異同、優(yōu)勢
欄 目:C#教程
本文標(biāo)題:C#使用LINQ中Enumerable類方法的延遲與立即執(zhí)行的控制
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6632.html
您可能感興趣的文章
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并打開的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10C#實(shí)現(xiàn)由四周向中心縮小的窗體退出特效
- 01-10Extjs4如何處理后臺json數(shù)據(jù)中日期和時(shí)間
- 01-10C#使用Dispose模式實(shí)現(xiàn)手動對資源的釋放
- 01-10C#3.0使用EventLog類寫Windows事件日志的方法
- 01-10C#中DataGridView常用操作實(shí)例小結(jié)
- 01-10C#編程獲取資源文件中圖片的方法
- 01-10C#使用windows服務(wù)開啟應(yīng)用程序的方法
- 01-10asp.net中XML如何做增刪改查操作


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已


