2015/01/28

C#.Net 使用LINQ做交集和聯集

Code:
using System;
using System.Windows.Forms;
using System.Linq;
namespace Sample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] number1 = { 1, 13, 55, 1, 88, 95, 33, 55, 1, 44, 100 };
        int[] number2 = { 1, 22, 44, 8, 66, 100, 5, 1, 1, 95 };

        /// <summary>
        /// 交集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            foreach (int number in (number1.Intersect(number2)
                .OrderBy(x => x > 0 ? x : int.MinValue)))
                textBox1.Text += number + Environment.NewLine;
        }

        /// <summary>
        /// 聯集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            foreach (int number in number1.Union(number2)
                .OrderBy(x => x > 0 ? x : int.MinValue))
                textBox1.Text += number + Environment.NewLine;
        }

    }

}

執行結果:

交集

聯集