1. 程式人生 > 實用技巧 >C# 語言整合查詢LINQ

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