LINQ 用法,返回结果不是在定义时取值,而是在调用时实时取值,有意思!

var names = new List<string> { "Nino o", "Alberto", "Juan", "Mike", "phi1" };
var namesWithJ = from n in names
where n.StartsWith("J")
orderby n
select n;
Console.WriteLine("First iteration");
foreach (string name in namesWithJ)
{
Console.WriteLine(name);
}
Console.WriteLine();
names.Add("John");
names.Add("Jim");
names.Add("Jack");
names.Add("Denny");
Console.WriteLine("second iteration");
foreach (string name in namesWithJ)
{
Console.WriteLine(name);
}

返回结果如下:

First iteration
Juan

second iteration
Jack
Jim
John
Juan

其他情况:

var names = new List<string> { "Nino o", "Alberto", "Juan", "Mike", "phi1" };
var namesWithJ = (from n in names
where n.StartsWith("J")
orderby n
select n).ToList();
Console.WriteLine("First iteration");
foreach (string name in namesWithJ)
{
Console.WriteLine(name);
}
Console.WriteLine();
names.Add("John");
names.Add("Jim");
names.Add("Jack");
names.Add("Denny");
Console.WriteLine("second iteration");
foreach (string name in namesWithJ)
{
Console.WriteLine(name);
}

返回结果如下:

First iteration
Juan

second iteration

Juan

上一篇:js模块化历程


下一篇:dojo grid 编辑问题