Linq

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;  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值