C# Linq語法(一)

目的:
使用Linq語法,這還滿方便的
有點像SQL語法,用在程式中撈對應的資料
這邊說明用Linq語法撈集合及XML檔案的方式

程式碼:





public partial class Form1 : Form
{
    List dog = new List();
    public Form1()
    {
        InitializeComponent();
        //先建一個集合
        Dog d1 = new Dog("小黃", "黃", "公", 18);
        dog.Add(d1);
        dog.Add(new Dog("小白", "白", "母", 15));
        dog.Add(new Dog("小花", "花", "母", 25));
        dog.Add(new Dog("小哈", "灰", "公", 36));
        dog.Add(new Dog("小土", "黃", "公", 24));
        dog.Add(new Dog("小黑", "黑", "母", 22));
        dog.Add(new Dog("小瑪", "白", "母", 8));
        dog.Add(new Dog("小柴", "黃", "公", 18));
        dog.Add(new Dog("小雪", "灰", "公", 26));
        dog.Add(new Dog("大獒", "黑", "母", 22));
        dog.Add(new Dog("小臘", "黑", "公", 42));
        dog.Add(new Dog("大黃", "黃", "公", 50));
        dog.Add(new Dog("大秋", "黃", "公", 48));
    }
    //------------------------------------------------------------------
    private void button1_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
           /* 普通的撈法如下:
            * for (int i = 0; i < dog.Count; i++)
            *       sb.Append(dog[i]);
            *            
            * foreach (Dog d in dog)
            *   sb.Append(d);
            *
            * 列舉語法,用LINQ來實現類SQL的語法(可供使用者挑選)
            * IEnumerable result = from d in dog
            *                          select d;
            *
            * 列舉語法配合var(萬用型別)
            * 可產生不論選出什麼,都不用管型態為何,再配合foreach更屌
            *更可用此法new個匿名類別,讓使用上更為方便
            */
        var result = from d in dog
                        where d.Sex == "母" && d.Weight >= 20
                        select new
                        {
                            //匿名類別
                        petName = d.Name,
                        petColor = d.Color,
                        petSex = d.Sex,
                        petWeight = d.Weight,
                        petIdeaWeight = d.Weight * 0.8
                        };

        foreach (var d in result)
                sb.Append(d.petName).Append("\t")
                    .Append(d.petColor).Append("\t")
                    .Append(d.petSex).Append("\t")
                    .Append(d.petWeight).Append("\t")
                    .Append(d.petIdeaWeight).Append("\r\n");
   
        textBox1.Text = sb.ToString();

    }
    //------------------------------------------------------------------
    private void button2_Click(object sender, EventArgs e)
    {
        var result = from d in dog
                        group d by d.Sex into sexGroup
                        select new
                        {
                            Sex = sexGroup.Key,
                            Count = sexGroup.Count(),
                            avgWeight = sexGroup.Average(x => x.Weight)
                            //平均體重,用到lamda的方式(private int Dog d(){return d.weight;})
                            //簡化成 x => x.Weight 其中x是匿名方法
                        };

        StringBuilder sb = new StringBuilder();
        foreach (var d in result)
            sb.Append(d.Sex).Append("\t")
                .Append(d.Count).Append("\t")
                .Append(d.avgWeight).Append("\r\n");

        textBox1.Text = sb.ToString();
    }
    //------------------------------------------------------------------
    private void button3_Click(object sender, EventArgs e)
    {
        //Linq 語法撈出XML中的資料
        //XML檔需自行準備    
        XDocument doc = XDocument.Load(@"C:\資料庫檔\中文北風XML\客戶.xml");
        var result = from xx in doc.Descendants("客戶")
                        where xx.Element("地址").Value.StartsWith("台中")//地址是台中開頭的客戶
                        select new 
                        {
                            name = xx.Element("公司名稱").Value,
                            person = xx.Element("連絡人").Value,
                            personJob = xx.Element("連絡人職稱").Value,
                            phone = xx.Element("電話").Value,
                            address = xx.Element("地址").Value
                        };

        StringBuilder sb = new StringBuilder();
        foreach (var d in result)
            sb.Append(d.name).Append("\t")
                .Append(d.person).Append("\t")
                .Append(d.personJob).Append("\t")
                .Append(d.phone).Append("\t")
                .Append(d.address).Append("\r\n");

        textBox1.Text = sb.ToString();

        dataGridView1.DataSource = result.ToList();
    }

}

留言

熱門文章