https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
基本结构
static void ListFiles(string rootDir, string searchParttern) { var ret = from fileName in Directory.GetFiles(rootDir, searchParttern) let fi = new FileInfo(fileName) orderby fi.Length descending, fileName ascending select fi; // print data }
where
var ret = from n in lst
where n >= 2
where n <= 4
select n
var ret = from n in lst
where n >= 2 && n <= 4 || n >= 8
select n
where还可以接受Lambda表达式做为过滤条件。一般将一些复杂的判断语句使用Lambda来表示。也可以使用Func<T,bool>定义一个委托来使用。
var ret = from person in personList where(p=>p.Salary > 10000) select person;
group by
有时需要将数据集合按某个key划分为多个集合
IEnumerable<IGrouping<int, Person>> ret = // int为分组的key类型,Person为元素类型 from person in personList group person by person.DepartmentID // 遍历 foreach(IGrouping<int, Person> group in ret) { Console.WriteLine(string.Format("Department:{0}",group.Key)); foreach(Person p in group) { Console.WriteLine(p.Name); } }
into
使用into可以进行延续查询。into之前的变量失效,而新定义的变量生效。
from person in personList where person.DepartmentID > 2 select person into p where p.Salary > 10000 select p;
使用from子句展开序列的序列
var ret = from word in Keywords from character in word select character; var numbers = new[]{1,2,3}; var ret = from word in Keywords from n in numbers select new{word, n};
结果去重Distinct( )
var ret =(from word in Keywords from character in word select character).Distinct( );
关联数据源join
var ret = from person in personList join department in departmentList on person.DepartmentID equals person.DepartmentID select new {PersonName = p.Name, DepartmentName = d.DepartmentName};
序列类型过滤OfType
var strRet = from s in mixArrayList.OfType<string>() select s;
计数Count
var ret = from str in Keywrods where str.Contains("L") select str; Console.WriteLine(ret.Count());
例子:
查询一篇文章中含有指定单词的句子
// Find sentences that contain all the terms in the wordsToMatch array. // Note that the number of terms to match is not specified at compile time. var sentenceQuery = from sentence in sentences let w = sentence.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },StringSplitOptions.RemoveEmptyEntries) where w.Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count() select sentence;