C#LINQ查询表达式用法

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

namespace Linq_1
{
    public 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 students = new[] { 
            new {Name ="张三",Sex= true,Age = 17},
            new {Name = "王二",Sex =true,Age = 20},
            new {Name = "罗霄",Sex =true,Age = 26}
            };
            /*  
            * 执行简单Linq查询 
            * 检索所有年龄在25岁以内的人 
            * 查询结果放在results变量中 
            * results变量的类型与数组persons相同
            */
            var results = from p in students
                          where p.Age <= 25
                          select p;

            foreach (var studet in results)
            {
                Console.WriteLine(studet.Name);
            }

            Console.WriteLine("===============集合的Linq查询=============");
            //集合构造者new List<Student>(){ }
            //对象构造者new Student(){ }
            List<Student> studentsList = new List<Student>()
            {   new Student(){ Name="张三", Sex=true, Age=25},
                new Student(){ Name="李文平", Sex=true, Age=22},
                new Student(){ Name="刘庆溪", Sex=true, Age=20}
            };

            var resultsList = from p in studentsList
                          where p.Age <= 25
                          select p;

            foreach (var studet in resultsList)
            {
                Console.WriteLine(studet.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

posted @ 2012-11-14 10:13  菜鸟程序猿  阅读(385)  评论(1编辑  收藏  举报