欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LinQ学习记录(一)

程序员文章站 2022-07-04 09:07:17
...

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;

可以填入多个数据,代表进行主要排列和次要排列