继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

linq学习笔记:int数组中找出偶数

繁星淼淼
关注TA
已关注
手记 149
粉丝 44
获赞 263

本例演示了如何从一个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写法,代码更简洁

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP