//1.数据源(names)的类型决定范围变量(name)的类型。
 //2.选择的对象的类型决定查询变量的类型。此处的 name 为一个字符串。因此,查询变量是一个 IEnumerable<string>。
            //3.在 foreach 语句中循环访问查询变量。因为查询变量是一个字符串序列,所以迭代变量也是一个字符串。
            List<string> names = new List<string>() { "factly","snwsky","josn","holly","host","lili","zhanghua"};

            IEnumerable<string> nameQuery = from name in names
                                            where name[0] == 'h'
                                            select name;
            IEnumerable<string> nameQuery1 = names.Where(name => name[0] == 'h');//Lambda表达式(方法语法)
            foreach (var str in nameQuery1)
            {
                Console.WriteLine(str);
            }

            //--转换源数据的查询(第一种方法)--------------------------------------------------------------------------
            //1.数据源(students)的类型决定范围变量(student)的类型。
            //2.select 语句返回 City 属性,而非完整的 Student 对象。因为City是一个字符串,所以studentQuery的类型参数是 string,而非 Student。
            //3.因为 studentQuery 是一个字符串序列,所以 foreach 循环的迭代变量也必须是 string。
            List<Student> students = new List<Student>() {
                new Student{First="Svetlana",Last="Omelchenko",ID=111,Street="123 Main Street",City="Seattle",Scores=new List<int>(){97, 92, 81, 60}},
                new Student{First="Claire",Last="O’Donnell",ID=112,Street="124 Main Street",City="Redmond",Scores=new List<int>(){75, 84, 91, 39}},
                new Student{First="Sven",Last="Mortensen",ID=113,Street="125 Main Street",City="Lake City",Scores= new List<int> {88, 94, 65, 91}},
            };
            IEnumerable<string> studentQuery = from student in students
                                               where student.First == "Svetlana"
                                               select student.City;
            foreach (string str in studentQuery)
            {
                Console.WriteLine("该学生所在的城市为:"+str);
            }

 

class Student
    {
        public string First { get; set; }
        public string Last { get; set; }
        public int ID { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public List<int> Scores;
   }

            //--转换源数据的查询(第二种方法)--------------------------------------------------------------------------
            //1.数据源(students)的类型决定范围变量(student)的类型。
            //2.因为 select 语句生成匿名类型,所以必须使用 var 隐式类型化查询变量。
            //3.因为查询变量的类型是隐式的,所以 foreach 循环中的迭代变量也必须是隐式的。
            var studentQuery1 = students.Where(student => student.First == "Svetlana").Select(stu => new { stu.City,stu.Last});//Lambda表达式(方法语法)
            foreach (var st in studentQuery1)
            {
                Console.WriteLine("{0},{1}",st.City,st.Last);
            }
            //--------------------------------------------------------------------------------------------------------
            Console.ReadKey();
        }

 posted on 2009-11-04 22:25  dongpo  阅读(401)  评论(0编辑  收藏  举报