C# 數組的交集、差集、並集
工作中經常會用這方面的知識來檢查那些字段是必須輸入的,那些是禁止輸入。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Collection
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] x = { 6,7,8,9,10};
13 int[] y = { 4,5,6,7,8};
14
15 var z1 = x.Except(y);
16 Console.WriteLine("Except: {0}",z1.Count());
17 foreach (var i in z1)
18 {
19 Console.Write(i + " ");
20 }
21
22 var z2 = x.Intersect(y);
23 Console.WriteLine("\nIntersect:{0}",z2.Count());
24 foreach (var i in z2)
25 {
26 Console.Write(i+" ");
27 }
28
29 var z3 = x.Union(y);
30 Console.WriteLine("\nUnion:{0}",z3.Count());
31 foreach (var i in z3)
32 {
33 Console.Write(i + " ");
34 }
35 Console.ReadKey();
36 }
37 }
38 }