LINQ(语言集成查询)的意图是提供一种统一且对称的方式,让程序员在广义的数据上得到和操作“数据”。通过使用LINQ,我们能够在C#程序语言内直接创建被陈伟查询表达式的实体。
1.简单的Linq查询式:
static void QueryOverInts()
{
int[] numbers = { 10, 20, 30, 40, 1, 4, 7, 9 };
IEnumerable<int> subset = from i in numbers where i < 10 select i;
foreach (int i in subset)
Console.WriteLine("Item:{0}", i);
}
(1)隐式局部变量:
var subset = from i in numbers where i < 10 select i;
(2)扩展方法:
往早先编译好的类型里添加新的成员;
(3)延迟执行:
在迭代内容前,LINQ不会真正做运算,这样可以为相同的容器多次应用相同的LINQ查询;
(4)立即执行:
以强类型容器来捕获LINQ查询结果,然后这个容器就不会再“连接”到LINQ表达式了;
int[] subsetIntArray = (from i in numbers where i < 10 select i).ToArray<int>();
List<int> subsetAsLisnt = (from i in numbers where i < 10 select i).ToList<int>();
2..查询运算符的内部表示:
(1)用查询运算符建立查询表达式:
static void QueryOverStrings()
{
string[] currentVideoGames = { "Morrowind", "BioShock", "Half Life 2:Episode 1", "The Darkness", "Daxter", "System Shock 2" };
IEnumerable<string> subset = from g in currentVideoGames where g.Length > 6 orderby g select g;
foreach (string s in subset)
Console.WriteLine("Item:{0}", s);
ReflectOverQueryResults(subset);
}
(2)使用Enumerable类型和Lambda表达式来建立查询表达式:
static void QueryStringWithEnumerableAndLambdas()
{
Console.WriteLine("*****Using Enumerable/Lambda Expressions*****");
string[] currentVideoGames = { "Morrowind", "BioShock", "Half Life 2:Episode 1", "The Darkness", "Daxter", "System Shock 2" };
var subset = currentVideoGames.Where(game => game.Length > 6).OrderBy(game => game).Select(game => game);
foreach (var game in subset)
Console.WriteLine("Item :{0}", game);
Console.WriteLine();
}
3.LINQ查询运算符:
(1)基本选择语法:
var result=from item in container select item;
(2)获取数据子集:
var result=from item in container where Boolean expression select item;
1787

被折叠的 条评论
为什么被折叠?



