Linq

2017-09-18  本文已影响13人  晓龙酱

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&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可以进行延续查询。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>

结果去重Distinct( )

<pre>
var ret =(from word in Keywords
from character in word
select character).Distinct( );
</pre>

关联数据源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>

计数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>

上一篇下一篇

猜你喜欢

热点阅读