第二章 LINQ to Objects基本用法
linq的基本语法:var result = from item in Container select item;
linq获取数据子集: var result = from item in container where booleanexpression select item;
Select用法:
var selectedItems = from item in items where item.ParentID == parentID orderby item.SortIndex descending ,item.Name ascending select item; |
where:根据条件查询,如果txtCustomerName中有值则匹配collection中的ClientName 是否包含这个txtCustomerName的值
var list=collection.Where(t => (txtCustomerName.Text.Trim().Length == 0 || t.ClientName.ToUpper().IndexOf(txtCustomerName.Text.Trim().ToUpper()) >= 0)); |
Filtering【过滤】
筛选指将结果集限制为只包含那些满足指定条件的元素的操作,下面的示例使用Where子句来从数组中筛选那些具有特定长度的字符串。
string[] words = { "the", "quick", "brown", "fox", "jumps" }; IEnumerable<string> query = from word in words where word.Length == 3 select word; |
Any和All
确定数据是否满足某个条件,返回布尔类型
bool anyUSA=customers.Any(c=>c.Country=="USA") //如果对于列表中的任意顾客,λ表达式是true,就返回true bool allAsia=customers.All(c=>c.Region=="Asia") //列表中的所有顾客来自亚洲,返回true。 |
LInq 递归实现
private BuildExpression(IEnumberable<string>enumberableList){...} //定义 function return factory =>{ BuildExpression(factory); //递归实现的function }; |
Linq查询中的常用函数
count<T>() 获取linq查询表达式返回的项数。对集合中的元素进行计数,还可以仅满足某一谓词函数的元素进行计数
list.Count(item=>item.Name=='test') //查询list中 name 为 test的记录条数
static void FunLinq()
{
int[] numbers = { 2, 10, 30, 15, 1, 22 };
//输出大于10的总数
int count = (from i in numbers where i > 10 orderby i select i).Count<int>();
Console.WriteLine(count);//输出:3
} |
Reverse<T>对linq结果集中的项进行反转
var newnumbers = from i in numbers select i; foreach (var p in numbers.Reverse()) { Console.WriteLine(p);//输出22 1 15 30 10 2 } |
orderby 对linq进行排序,默认是正序。默认为升序(A到Z),可以添加descending关键字指定降序(Z到A)
//排序(正序)
string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2" };
var newn = from i in games orderby i ascending select i;
foreach (var p in games)
{
Console.Write(p+",");//
} |
用语法排序
list.OrderBy(entity=>entity.CreateDate); //entity 表示 T的一个实例,按照 createdate 顺序排列,反之 则使用 listOrderByDescing逆序排序
varquerResults=names.OrderByDescending(n=>n)
多级排序
var queryResult= from c in customers Orderby c.Region,c.Country,c.City Select new(c.ID,c.Region,c.County,C.City) |
方法语法
var queryResult=customers.OrderBy(c=>c.Region).ThenByDescending(c=>c.County). ThenBy(c=>c.City).select(c=>new{c.ID,c.Region,c.Country,c.City}) |
Distinct()移除数据中的重复项目
//排序(正序)
string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2", "Shock2"};
var newn = from i in games orderby i ascending select i;
foreach (var p in games.Disinct())
{
Console.Write(p+",");//
} |
聚合操作
//聚合操作 //最大值 var maxi =( from i in games orderby i ascending select i).Max(); //最小值 var mini = (from i in games orderby i ascending select i).Min(); //平均值 var avar = (from i in numbers orderby i ascending select i).Average(); //总和 var sum = (from i in numbers orderby i ascending select i).Sum();
list.Sum(item=>item.Quantity); //合计,合计list中的quantity 字段 querResults.Sum(n=>(long)n) //无参数返回32位int类型,n=>(long)n转化为64位, 防止溢出 |