linq中let关键字学习
生活随笔
收集整理的這篇文章主要介紹了
linq中let关键字学习
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
linq中l(wèi)et關(guān)鍵字就是對子查詢的一個別名,let子句用于在查詢中添加一個新的局部變量,使其在后面的查詢中可見。
?
linq中l(wèi)et關(guān)鍵字實例
?
1、傳統(tǒng)下的子查詢與LET關(guān)鍵字的區(qū)別
C# 代碼 ??復(fù)制 static void Main(string[] args) { int[] numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; //傳統(tǒng)下的子查詢做法 var query = from num in numbers select num * (from n in numbers where n % 2 == 0 select n).Count(); //使用LET關(guān)鍵字的做法 var query = from num in numbers let evenNumbers = from n in numbers where n % 2 == 0 select n select num * evenNumbers.Count(); foreach (var item in query) { Console.WriteLine(item); } Console.Read(); }?
2、把每個單詞開頭包含a或者e的找出來
C# 代碼 ??復(fù)制 using System; using System.Linq; public class Test { static void Main(string[] args) { string[] strings = { "A penny saved is a penny earned.", "The aaxly sdj", "the pa is no" }; var query = from sentence in strings let words = sentence.Split(' ')//用空格分割成數(shù)組 from word in words let w = word.ToLower()//把每個字母小寫 where w[0] == 'a' || w[0] == 'e' select word; foreach (var s in query) { Console.WriteLine(s); } Console.ReadLine(); } }?
3、linq實例3
C# 代碼 ??復(fù)制 var query = from p in persons let friendlyName = p.Gender == "男" ? "Mr" : "Ms" + p.Name select new { UserID = p.ID, FriendName = friendlyName }; foreach (var item in query) { Console.WriteLine("No:{0},Friendly Name:{1}", item.UserID, item.FriendName); }?
4、linq實例4
C# 代碼 ??復(fù)制 public class Singer { public string Name { set; get; } public int Age { set; get; } } List<Singer> list = new List<Singer>(){ new Singer{Name="zhangs" ,Age=21}, new Singer{Name="zhangs",Age=25}, new Singer{Name="margy",Age=21} }; var query = from a in list let b = a.Name let c=a.Age where b =="zhangs" & c>21 select a; foreach (var item in query) { Response.Write("姓名: "+item.Name+" 年齡:"+item.Age); } //結(jié)果 姓名: zhangs 年齡:25 //使用let 建立了個范圍變量,這個范圍變量在后續(xù)的where子句中使用,如果不使用let子句,where子句的表達式將寫成這樣: //where a.Name=="zhangs" & a.Age>21</span>轉(zhuǎn)載于:https://www.cnblogs.com/ranran/p/4059324.html
總結(jié)
以上是生活随笔為你收集整理的linq中let关键字学习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PostMessage发送字符串和结构体
- 下一篇: Activiti配置实例以及Spring