C#LINQ查詢表達式用法


 

>

代碼如下,謝謝閱讀,控制台應用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace LinqQueryDemo
{
    class Student
    {
        public string Name { get; set; }
        public bool Sex { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("===============數組的Linq查詢=============");
            //隱式類型化數組
            var persons = new[]{
                new {Name="王二" ,Sex=true,Age=17},
                new {Name="張三", Sex=true,Age=15},
                new {Name="李四", Sex=true,Age=21}
            };
            /* 
             * 執行簡單Linq查詢
             * 檢索所有年齡在25歲以內的人
             * 查詢結果放在results變量中
             * results變量的類型與數組persons相同
             */
            var results = from p in persons
                          where p.Age <= 25
                          select p;
            foreach (var person in results)
            {
                Console.WriteLine(person.Name);
            }
            Console.WriteLine("===============集合的Linq查詢=============");
            //集合構造者new List<Student>(){ }
            //對象構造者new Student(){ }
            List<Student> students = new List<Student>(){ new Student(){ Name="張三", Sex=true, Age=25},
                new Student(){ Name="李文平", Sex=true, Age=22},
                new Student(){ Name="劉慶溪", Sex=true, Age=22}
            };
            var stus = from p in students
                       where p.Age <= 25
                       select p;
            foreach (var stu in stus)
            {
                Console.WriteLine(stu.Name);
            }
            /* 執行簡單Linq查詢XML
             * 檢索所有年齡在25歲以內的學生信息
             * 查詢結果放在stuResults變量中
             */
Console.WriteLine("===============XML的Linq查詢=============");
            string xml = "<students><student><Name>王二</Name><Sex>true</Sex><Age>28</Age></student><student><Name>李四</Name><Sex>true</Sex><Age>22</Age></student><student><Name>張三</Name><Sex>true</Sex><Age>25</Age></student></students>";
            using (StringReader reader = new StringReader(xml))//創建字符串讀取器
            {
                XDocument xDoc = XDocument.Load(reader);//裝載xml
                var stuResults = from p in xDoc.Element("students").Elements("student")
                                 where Convert.ToInt32(p.Element("Age").Value) <= 25
                                 select p;
                foreach (var stu in stuResults)
                {
                    Console.WriteLine(stu.Element("Name").Value);
                }
            }
        }
    }
}

尊重作者,轉發請注明出處:http://www.cnblogs.com/minotmin
謝謝閱讀,有錯請指出,不甚感激。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM