Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

จัดกลุ่มตามตัวดำเนินการใน C #


ใช้กลุ่มตามตัวดำเนินการใน C# เพื่อแยกผลลัพธ์ของนิพจน์ออกเป็นส่วนๆ

สมมติว่าต่อไปนี้คืออาร์เรย์ของเรา –

int[] a = { 5, 10, 15, 20, 25, 30 };

ตอนนี้โดยใช้ Group by และ orderby เราจะพบองค์ประกอบที่มากกว่า 20 −

var check = from element in a orderby element group element by chkGreater(element);

ต่อไปนี้เป็นรหัสที่สมบูรณ์ -

ตัวอย่าง

using System;
using System.Linq;
class Demo {
   static void Main() {
      int[] a = { 5, 10, 15, 20, 25, 30 };
      var check = from element in a orderby element group element by chkGreater(element);
      foreach (var val in check) {
         Console.WriteLine(val.Key);
         foreach (var res in val) {
            Console.WriteLine(res);
         }
      }
   }
   static bool chkGreater(int a) {
      return a >= 20;
   }
}

ผลลัพธ์

False
5
10
15
True
20
25
30