(200-07-21) LINQ 匿名型別 與 LINQ 基本查詢語法

摘要:(200-07-21) LINQ

匿名型別

 

      //Strong Type
            String str1 = null;
            str1 = "eric"; //字串物件位址給str1
            //定義匿名型別
            var str2 = "Linda"; //透過Assign值 決定該變數型別
            //str2 = 12345; 並非可變型別 Variant

            MessageBox.Show(str2.GetType().ToString());

LINQ 基本查詢語法

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace linqwin
{
    public partial class Form1 : Form
    {
        //Data Field
        // 字串陣列
        private String[] names =new String[] { "Eric Chen", "Bill Lin", "Sam Lu", "Barry Chen" };

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //泛型集合
            System.Collections.Generic.List<String> col = new List<string>();
            //逐一參考陣列每一個元素
            foreach (String name in names)
            {
                //比對相對項目
                if (name.Contains("Chen"))
                {
                    //暫存著(參考著)
                    col.Add(name);
                }
            }
            // 鋪答案
            foreach(String s in col)
            {

                this.listBox1.Items.Add(s);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //匿名型別
            var items = from name in names
                        where name.Contains("Chen")
                        select name;
            MessageBox.Show(items.GetType().ToString());
            foreach (var s in items)
            {
                MessageBox.Show(s.GetType().ToString());
                this.listBox1.Items.Add(s);
            }
                
        }
    }
}

課程補充

 

上課範列