前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >linq学习笔记(一)

linq学习笔记(一)

作者头像
菩提树下的杨过
发布2018-01-22 16:54:50
5350
发布2018-01-22 16:54:50
举报

本例演示了如何从一个int数组中找出偶数,并将结果从大小到排序

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace LinqDemo

{
    class Program

    {

        static int[] numbers = { 1, 3, 4, 5, 6, 7, 8, 9, 10, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11 };

        static void Main(string[] args)

        {

            Traditonal();

            Console.WriteLine("----------------------");

            LinqMethod();

            Console.ReadLine();

        }


        /// <summary>

        /// 传统写法

        /// </summary>

        static void Traditonal() 

        {
           
            List<int> SelectedNumbers = new List<int>();

            foreach (int i in numbers)

            {

                if (i % 2==0)

                {

                    SelectedNumbers.Add(i);                    

                }               

            }           

           
            SelectedNumbers.Sort(SortDesc); //.net1.0写法           

            for (int i = 0; i < SelectedNumbers.Count; i++)

            {

                Console.WriteLine(SelectedNumbers[i]);

            }
           
        }

        /// <summary>

        /// 逆顺排序(配合传统写法)

        /// </summary>

        /// <param name="x"></param>

        /// <param name="y"></param>

        /// <returns>1(x大于y),0(x等于y),-1(x小于y)</returns>

        static int SortDesc(int x,int y) 

        {

            //if (x < y) 

            //{

            //    return 1;

            //}

            //else if (x == y)

            //{

            //    return 0;

            //}

            //else 

            //{

            //    return -1;

            //}//也可以简写为下面的一行

            return y - x;

        }

        /// <summary>

        /// Linq的写法

        /// </summary>

        static void LinqMethod() 

        {
          
            var SelectedNumbers = from number in numbers where (number % 2 == 0) orderby number descending select number;

            foreach (var i in SelectedNumbers)

            {

                Console.WriteLine(i);

            }           

        }
       
    }

}

可以看出用Linq写法,代码更简洁

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2008-02-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档