码迷,mamicode.com
首页 > 其他好文 > 详细

linq的基本使用

时间:2017-11-05 12:12:29      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:pre   ==   偶数   for   sel   基本   foreach   sele   blog   

1.查询所有的偶数

            int[] str = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
            var elist = from s in str
                        where s % 2 == 0
                        select s;
            foreach (int i in elist)
            {
                Console.WriteLine("偶数有:{0}", i);
            }
            Console.ReadKey();

2.查询所有的偶数 从大到小排序

            int[] str = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
            var elist = from s in str
                        where s % 2 == 0
                        orderby s descending ////查询所有偶数并倒序排序,就是从大到小排序。
                        select s;
            foreach (int i in elist)
            {
                Console.WriteLine("偶数有:{0}", i);
            }

3.查询对象结果投影一个新的对象

    class Student
    {
        public string name { get; set; }
        public string sex { get; set; }
        public int age { get; set; }
    }


            List<Student> list = new List<Student>()
            {
                new Student(){name=@"haha",sex="",age=78},
                new Student(){name=@"hehe",sex="",age=9},
                new Student(){name=@"heihei",sex="",age=56}
            };
            //var stu = from s in list
            //          where s.age > 10
            //          select s;
            //foreach (var bb in stu)
            //{
            //    Console.WriteLine("{0},{1},{2}", bb.name, bb.age, bb.sex);
            //}
            //将查询结果直接放入一个新的对象
            var stu = from s in list
                      where s.age > 10
                      select new { Newname = s.name, Newsex = s.sex, Newage = s.age };
            foreach (var bb in stu)
            {
                Console.WriteLine("{0},{1},{2}", bb.Newname, bb.Newage, bb.Newsex);
            }

4.获取集合对象的,长度大于7对象。

            string[] arr = { "qwewrtyywe", "asdfghkl", "zxcvbnm", "abcqqqqqq" };
            IEnumerable<string> str = from s in arr
                                      where s.Length > 6
                                      select s;
            foreach (var ab in str)
            {
                Console.WriteLine(ab);
            }

 

linq的基本使用

标签:pre   ==   偶数   for   sel   基本   foreach   sele   blog   

原文地址:http://www.cnblogs.com/zqrios/p/7786976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!