基本LINQ表达式
- 使用链式表达式
场景:查询文件系统中的文件为例
var path = @"c://";
var filespath = Directory.GetFiles(path);
var x = filespath.Select(filepath =>
{
var fileinfo = new FileInfo(filepath);
return new { fileinfo.Name, fileinfo.Length };
}).Where(n => n.Length>0 );
此次只是用到了两种为案例还有 orderby、Thenby 排序 group分组 Join 连接 Distinct 删除重复 union 并集 Intersect 交集 concat 连接 selectMany 延迟查询
注意:orderby只出现一次,其后跟Thenby
- 使用类似sql语句表示
//LINQ查询表达式
var query = from filepath in Directory.GetFiles(path)
let fileinfo = new FileInfo(filepath)
where fileinfo.Length >0
orderby fileinfo.Length descending
group fileinfo by fileinfo.Length into groups
from item in groups
select new {groups.Key,count= groups.Count(),item.Name};
有点类似数据库的写法,好处是可以扩展,仅供参考,有错误请告知