LINQ之let关键字

时间:2022-11-27 11:17:05

let子句用于在LINQ表达式中存储子表达式的计算结果。let子句创建一个范围变量来存储结果,变量被创建后,不能修改或把其他表达式的结果重新赋值给它。
此范围变量可以再后续的LINQ子句中使用。

实例1

 int[] numbers = new[] { , , , , , , , , ,  };

 //传统下的子查询做法
//var query = from num in numbers
// select num * (from n in numbers
// where n % 2 == 0
// select n).Count(); //使用LET关键字的做法
var query = from num in numbers
let evenNumbers = from n in numbers
where n % ==
select n
select num * evenNumbers.Count(); foreach (var item in query)
{
Console.WriteLine(item);
}

运行结果:0 5 10 15 20 25 30 35 40 45

实例2

 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(' ')//用空格分割成数组
from word in words
let w = word.ToLower()//把每个字母小写
where w[] == 'a' || w[] == 'e'
select word; foreach (var s in query)
{
Console.WriteLine(s);
}

运行结果:LINQ之let关键字

实例3

 List<Person> persons = new List<Person>
{
new Person { ID = "", Name = "张三" ,Gender = "男" , Age = },
new Person { ID = "", Name = "李四" ,Gender = "女" , Age = },
new Person { ID = "", Name = "王五" ,Gender = "女" , Age = },
new Person { ID = "", Name = "赵六" ,Gender = "男", Age = }
};
var query = from p in persons
let friendlyName = p.Gender == "男" ? "Mr" + p.Name : "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);
}

运行结果:LINQ之let关键字

实例4

 List<Person> persons = new List<Person>
{
new Person { ID = "", Name = "张三" ,Gender = "男" , Age = },
new Person { ID = "", Name = "李四" ,Gender = "女" , Age = },
new Person { ID = "", Name = "王五" ,Gender = "女" , Age = },
new Person { ID = "", Name = "赵六" ,Gender = "男", Age = }
}; var query = from p in persons
let gender = p.Gender
let age = p.Age
where age > && gender == "女"
select p;
foreach (var item in query)
{
Console.WriteLine("姓名: " + item.Name + " 年龄:" + item.Age);
}

运行结果:LINQ之let关键字