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 @   echo-efun  阅读(172)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示