C# 语言集成查询LINQ

1.引用

using System;
using System.Collections.Generic;
using System.Linq;

2.打印一副扑克牌

        static void Main(string[] args)
        {
            var pokers = from s in Suits()
                         from r in Ranks()
                         select s+r+"\n";
                               //select new {s,r};
            foreach (var card in pokers)
            {
                Console.Write(card+" ");
            }
        }

        static IEnumerable<string> Suits()
        {
            yield return "clubs";   //声明为一个迭代器
            yield return "diamonds";
            yield return "hearts";
            yield return "spades";
            yield break;
            yield return "此语句不会运行";     //此语句不会运行
        }

        static IEnumerable<string> Ranks()
        {
            yield return "2";
            yield return "3";
            yield return "4";
            yield return "5";
            yield return "6";
            yield return "7";
            yield return "8";
            yield return "9";
            yield return "10";
            yield return "J";
            yield return "Q";
            yield return "K";
            yield return "A";
            yield break;
        }

 

 

3. 查询实例 

        static void Main(string[] args)
        {
int[] scores = new int[] { 97, 92, 81, 65 };

            ///query实现
            IEnumerable<int> query = from score in scores
                                     where score > 80 && score < 95
                                     orderby score
                                     select score;

            ///方法实现,结果同query实现
            IEnumerable<int> query2 = (scores.Where(score => score > 80)).Where(score => score < 95).OrderBy(n => n);
            Console.WriteLine();
            Console.WriteLine();

            foreach (int score in query)
            {
                Console.WriteLine($"分数低于95,高于80的分数:{score}");
            }

            Console.WriteLine();
            Console.WriteLine();

            foreach (int score in query2)
            {
                Console.WriteLine($"分数低于95,高于80的分数:{score}");
            }

            Console.WriteLine();

        }

 

 

 

 

4.查询关键字

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/query-keywords

 

posted @ 2020-12-19 16:13  echo-efun  阅读(183)  评论(0)    收藏  举报