https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
基本結(jié)構(gòu)
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表達(dá)式做為過濾條件。一般將一些復(fù)雜的判斷語句使用Lambda來表示。也可以使用Func<T,bool>定義一個委托來使用。
var ret = from person in personList
where(p=>p.Salary > 10000)
select person;
group by
有時需要將數(shù)據(jù)集合按某個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.<font color=blue>Key</font>));
foreach(Person p in group)
{
Console.WriteLine(p.Name);
}
}
into
<font size=2>使用into可以進行延續(xù)查詢。into之前的變量失效,而新定義的變量生效。</font>
<pre>
from person in personList
where person.DepartmentID > 2
select person
<font color=blue>into</font> p
where p.Salary > 10000
select p;
</pre>
使用from子句展開序列的序列
<pre>
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};
</pre>
結(jié)果去重Distinct( )
<pre>
var ret =(from word in Keywords
from character in word
select character).Distinct( );
</pre>
關(guān)聯(lián)數(shù)據(jù)源join
<pre>
var ret =
from person in personList
<font color=blue>join</font> department <font color=blue>in</font> departmentList <font color=blue>on</font> person.DepartmentID equals person.DepartmentID
select new {PersonName = p.Name, DepartmentName = d.DepartmentName};
</pre>
序列類型過濾OfType
<pre>
var strRet = from s in mixArrayList.<font color=blue>OfType<string>()</font>
select s;
</pre>
計數(shù)Count
<pre>
var ret = from str in Keywrods
where str.Contains("L")
select str;
Console.WriteLine(ret.Count());
</pre>
例子:
查詢一篇文章中含有指定單詞的句子
<pre>
// 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.<font color=blue>Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count()</font>
select sentence;
</pre>