LinQ的所有操作就是基于可迭代对象的操作的,最简单的当然是数组的处理
//第一个例子:最简单的例子
String[] strs = {"zhangran","zhangxiaoran","xiaozhangran","ranxiaozhang","ranzhangxiao","xiaoxiaoran" };
var index = from n in strs
where n.StartsWith("z")//where 是限制运算符
select n;//select 这是必选的
foreach(String i in index)
{
Console.WriteLine(i);
}
Console.ReadKey();
//上面例子的变种用方法来实现查询
String[] strs = { "zhangran", "zhangxiaoran", "xiaozhangran", "ranxiaozhang", "ranzhangxiao", "xiaoxiaoran" };
var index = strs.Where(n=>n.StartsWith("z"));
foreach (String i in index)
{
Console.WriteLine(i);
}
Console.ReadKey();
//第二个例子:对查找结果进行排序
/*String[] strs = {"zhangran","zangxiaoran","zixiaozhangran","ranxiaozhang","ranzhangxiao","xiaoxiaoran" };
var index = from n in strs
where n.StartsWith("z")
orderby n//其它的选择 orderby descending ,orderby n.Substring(n.Length-1)
select n;
foreach(String i in index)
{
Console.WriteLine(i);
}
Console.ReadKey();
*/
//对上面的变种:用方法实现排序
/* String[] strs = { "zhangran", "zangxiaoran", "zixiaozhangran", "ranxiaozhang", "ranzhangxiao", "xiaoxiaoran" };
//var index = strs.OrderBy(n=>n).Where(n=>n.StartsWith("z"));
//var index = strs.OrderByDescending(n => n).Where(n => n.StartsWith("z"));
var index = strs.OrderBy(n=>n.Substring(n.Length-1)).Where(n => n.StartsWith("z"));
foreach(String i in index)
{
Console.WriteLine(i);
}
Console.ReadKey();
*/
//聚合运算符的使用
/*
int [] ints = {1,2,3,4,5,6,7,8,9};
var index = from n in ints
where n>1
select n;
//此处不再是foreach遍历
Console.WriteLine(index.Count());
Console.WriteLine(index.Average());
Console.WriteLine(index.Min());
Console.WriteLine(index.Max());
Console.WriteLine(index.Sum(n =>n+1));
Console.ReadKey();
*/