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
谢谢阅读,有错请指出,不甚感激。

posted on 2012-09-25 17:21  程序猴chengxuhou.com  阅读(4036)  评论(0编辑  收藏  举报

导航