Linq

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表達式做為過濾條件。一般將一些復雜的判斷語句使用Lambda來表示。也可以使用Func<T,bool>定義一個委托來使用。

var ret = from person in personList
where(p=>p.Salary > 10000)
select person;

group by

有時需要將數(shù)據(jù)集合按某個key劃分為多個集合

IEnumerable&lt;IGrouping&lt;int, Person&gt&gt; ret =    // int為分組的key類型,Person為元素類型 
from person in personList
group person by person.DepartmentID

// 遍歷
foreach(IGrouping&lt;int, Person&gt; 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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容