栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

本例演示了如何从一个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();

           

        }


        /// 


        /// 传统写法
        /// 

        static void Traditonal() 
        {
            
            List SelectedNumbers = new List();
            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]);
            }
            
        }


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

        /// 
        /// 
        /// 1(x大于y),0(x等于y),-1(x小于y)
        static int SortDesc(int x,int y) 
        {
            //if (x < y) 
            //{
            //    return 1;
            //}
            //else if (x == y)
            //{
            //    return 0;
            //}
            //else 
            //{
            //    return -1;
            //}//也可以简写为下面的一行
            return y - x;

        }

        /// 
        /// Linq的写法
        /// 

        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写法,代码更简洁

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/231493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号