LinQ学习记录(一)
1.from 子句
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums = from num in numbers
where num < 5
select num;
foreach (int i in lowNums)
{
Console.Write(i + " ");
}
查询语句会使用from进行开头
2.复合 from 子句
var scoreQuery = from student in students
from score in student.Scores
where score > 90
select new { Last = student.LastName, score };
当内部数据源本身是序列(可进行迭代)的时候,便可以使用复合from,对序列内的数据进行调用
——————————————————————
var joinQuery2 =
from lower in lowerCase
where lower != 'x'
from upper in upperCase
select new { lower, upper };
使用from访问多个数据源
3. where 子句
var queryLowNums =
from num in numbers
where num < 5
select num;
where 子句用在查询表达式中,用于指定一个返回的标准
其可以出现在除了第一句和最后一句之外的所有位置
如果删除where,则会返回所有的数据
可以使用&&、||来指定多个不同的标准(谓词)
——————————————————————
var queryEvenNums =
from num in numbers
where IsEven(num)
select num;
static bool IsEven(int i)
{
return i % 2 == 0;
}
甚至可以指定返回值为bool的方法,来作为挑选的“标准”
4. select 子句
IEnumerable<int> queryHighScores =
from score in Scores
where score > 80
select score;
select 子句指定在执行查询时产生的值的类型
查询表达式必须以 select 子句或 group 子句结尾
5. group 子句
var studentQuery1 =
from student in students
group student by student.Last[0];
使用group by对数据进行分组,分组之后的结果需要嵌套foreach循环进行取出
——————————————————————————
var wordGroups2 =
from w in words2
group w by w[0] into grps
where (grps.Key == 'a' || grps.Key == 'e' || grps.Key == 'i'
|| grps.Key == 'o' || grps.Key == 'u')
select grps;
可以使用into关键字进行逻辑的附加,此时要用其他关键字进行结尾
by之后的键类型可以按照字符串、布尔值、复合键等条件进行分组
范例如下:
var studentQuery3 =
from student in students
group student by student.Last;
//字符串
var booleanGroupQuery =
from student in students
group student by student.Scores.Average() >= 80;
//布尔值
var studentQuery =
from student in students
let avg = (int)student.Scores.Average()
group student by (avg / 10) into g
orderby g.Key
select g;
//数值范围
group person by new {name = person.surname, city = person.city};
//复合键
6. into标识符
其作用是将 group、join 或 select 子句的结果,存储至新标识符,代表着一种“延续”
var wordGroups1 =
from w in words
group w by w[0] into fruitGroup
where fruitGroup.Count() >= 2
select new { FirstLetter = fruitGroup.Key, Words = fruitGroup.Count() };
7. orderby 子句
可以使返回值按照升序或者降序进行排序
如果是字符串,将会以A开始
IEnumerable<string> sortAscendingQuery =
from fruit in fruits
orderby fruit ascending
select fruit;
IEnumerable<string> sortDescendingQuery =
from w in fruits
orderby w descending
select w;
ascending为默认关键字,可以进行省略,代表正序进行排列‘
descending关键字代表以倒序进行排列
————————————————————————————
IEnumerable<Student> sortedStudents =
from student in students
orderby student.Last ascending, student.First ascending
select student;
可以填入多个数据,代表进行主要排列和次要排列
上一篇: 第十二章 Proxy
推荐阅读
-
Java学习记录:纠错Junit单元测试遇到的initializationerror:method initializationerror not found
-
C++学习摘要记录
-
PHP学习总结(一),php学习总结
-
python字符串的学习记录
-
HTML DOM(学习笔记一)_html/css_WEB-ITnose
-
6-22日学习记录
-
韩顺平_PHP软件工程师玩转算法公开课(第一季)01_算法重要性_五子棋算法_汉诺塔_回溯算法_学习笔记_源代码图解_PPT文档整理
-
那些年一起学习的PHP(二)_php基础
-
深入DropDownList用法的一些学习总结分析
-
(一)学习SpringBoot介绍