每天学习一点点,成功增加一大步

.Net Core 笔记: LINQ

C# zhanghui 2355℃

之前在使用 Node 练习或是写项目时,经常听 C# 中有个 Linq 对于数据集合的处理非常好用,虽然 node 里面也有这个插件,但从我目前的使用场景来说不是很多,这回接触 .net core 后就想去接触一下,不认识不知道它的优势,一接触就吓一跳,这个东西确实如传闻中的牛气。你实践后会发现它同有个东西非常相似 ,那就是 SQL语句。下面记录几个例子。

一、基础级的应用

1.1、简单的数字筛选处理

/// <summary>
/// 简单的数字筛选处理
/// </summary>
/// <returns>
/// [97,92,81]
/// </returns>
private dynamic sample1()
{
int[] scores = new int[] { 97, 92, 81, 60 };
IEnumerable scoresQuery = from score in scores where score > 60 select score;
return Json(scoresQuery);
}

1.2、将筛选出来的数组进行排序

/// <summary>
/// 将筛选出来的数组进行排序
/// </summary>
/// <returns>[81,92,97]</returns>
private dynamic sample2()
{
int[] scores = new int[] { 97, 92, 81, 60 };
IEnumerable scoresQuery = from score in scores where score > 60 orderby score ascending select score;
// IEnumerable scoresQuery = from score in scores where score > 60 orderby score descending select score;
return Json(scoresQuery);
}

1.3 let 应用

/// <summary>
/// let 应用
/// </summary>
/// <returns>
/// {"namesQuery":["Svetlana","Claire","Sven","Cesar"]}
/// </returns>
private dynamic sample3()
{
string[] names = { "Svetlana Omelchenko", "Claire O'Donnell", "Sven Mortensen", "Cesar Garcia" };
IEnumerable namesQuery =
from name in names
let firstName = name.Split(new char[] { ' ' })[0]
select firstName;
return new { namesQuery };
}

 

转载请注明:隨習筆記 » .Net Core 笔记: LINQ

喜欢 (0)