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

เมธอด Queryable Union ใน C# LINQ


ภาพรวม

เมธอด Union() ใน LINQ ใช้รวมสองลำดับโดย เอาเฉพาะค่าที่ไม่ซ้ำกัน (distinct) คือ ยูเนียนของเซต (set union)

รูปแบบการใช้งาน

int[] arr1 = { 29, 40, 15, 55, 70, 30, 90 };
int[] arr2 = { 30, 36, 40, 18, 15, 55, 75 };
var union = arr1.AsQueryable().Union(arr2); // ลบซ้ำอัตโนมัติ

ตัวอย่างโค้ดเต็ม

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

public class Demo
{
    public static void Main()
    {
        int[] arr1 = { 29, 40, 15, 55, 70, 30, 90 };
        int[] arr2 = { 30, 36, 40, 18, 15, 55, 75 };
        IEnumerable res = arr1.AsQueryable().Union(arr2);
        foreach (int a in res) Console.WriteLine("{0} ", a);
    }
}

ผลลัพธ์

29 40 15 55 70 30 90 36 18 75

ข้อสังเกต

  • ผลลัพธ์ ไม่มีลำดับที่รับประกัน (unordered) - ใช้ .OrderBy(x => x) หากต้องการเรียง
  • ใช้ default equality comparer - สำหรับออบเจ็กต์ต้อง implement IEquatable<T> หรือส่ง comparer เข้าไป
  • ต่างจาก Concat() ที่รวมทุกอย่าง (รวมค่าซ้ำ)
  • ต่างจาก Intersect() ที่เอาเฉพาะค่าที่ซ้ำ (intersection)
  • ต่างจาก Except() ที่เอาค่าที่อยู่ในตัวแรกแต่ไม่อยู่ในตัวที่สอง