linq中l(wèi)et關(guān)鍵字就是對(duì)子查詢的一個(gè)別名,let子句用于在查詢中添加一個(gè)新的局部變量,使其在后面的查詢中可見(jiàn)。
linq中l(wèi)et關(guān)鍵字實(shí)例
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、把每個(gè)單詞開(kāi)頭包含a或者e的找出來(lái)
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()//把每個(gè)字母小寫
where w[0] == 'a' || w[0] == 'e'
select word;
foreach (var s in query)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
3、linq實(shí)例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實(shí)例4
C# 代碼 復(fù)制public class Singer
{
public string Name { set; get; }
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注