c#数组用linq语句查询奇偶数并排序
c#数组用linq语句查询奇偶数并排序
使用LINQ和Lambda表达式根据特定条件来查询数组
int[] names = { 8,9,22,23,7,2}; int[] evens = names.Where(p1 => p1 % 2 == 0).OrderByDescending(p1=>p1).ToArray(); //查找所以偶数并排序 Console.WriteLine("偶数:"+string.Join(",",evens)); string evens_str = string.Join(",",evens); Console.WriteLine("偶数string:"+evens_str); int[] oadds = names.Where(p1 => p1 % 2 != 0).OrderByDescending(p1 => p1).ToArray(); Console.WriteLine("偶数:" + string.Join(",", oadds)); string evens_str1 = string.Join(",", oadds); Console.WriteLine("偶数string:" + evens_str1);
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinqLearning { class Program { private static int[] GenerateLotsOfNumbers(int count) { Random generator = new Random(0); int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = generator.Next(); } return result; } static void Main(string[] args) { int[] numbers = GenerateLotsOfNumbers(12345678); var queryResults = from n in numbers where n < 1000 orderby n descending select n; Console.WriteLine("查询语法排序结果:"); DateTime start = DateTime.Now; foreach (var item in queryResults) Console.WriteLine(item); Console.WriteLine("消耗时间:{0}",DateTime.Now-start); var queryResult = numbers.OrderByDescending(n => n).Where(n => n < 1000); Console.WriteLine("方法排序结果(排序字段在前):"); start = DateTime.Now; foreach (var item in queryResult) Console.WriteLine(item); Console.WriteLine("消耗时间:{0}", DateTime.Now - start); var query = numbers.Where(n => n < 1000).OrderByDescending(n => n); Console.WriteLine("方法排序结果(排序字段在后):"); start = DateTime.Now; foreach (var item in query) Console.WriteLine(item); Console.WriteLine("消耗时间:{0}", DateTime.Now - start); Console.ReadKey(); } } }
欢迎讨论,相互学习。
cdtxw@foxmail.com