排序与排序依据int数组 [英] Sort an int array with orderby

查看:108
本文介绍了排序与排序依据int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以升序排序我的int数组

I would like to sort my int array in ascending order.

首先,我让我的数组的副本:

first I make a copy of my array:

int[] copyArray = myArray.ToArray();



然后我想它按升序这样的排序:

Then I would like to sort it in ascending order like this:

 int[] sortedCopy = from element in copyArray 
                    orderby element ascending select element;



但我得到一个错误,入选被highligted和错误是:
不能隐式转换类型'system.linq.iorderedenumerable'到'INT []'。

But I get a error, "selected" gets highligted and the error is: "cannot implicitly convert type 'system.linq.iorderedenumerable' to 'int[]'"

推荐答案

您需要调用 ToArray的()末实际转换有序序列到一个数组。 LINQ使用的懒惰的评价的,这意味着直到调用 ToArray的()了ToList()或将不会执行一些其他类似方法的中间处理(在这种情况下,排序)。

You need to call ToArray() at the end to actually convert the ordered sequence into an array. LINQ uses lazy evaluation, which means that until you call ToArray(), ToList() or some other similar method the intermediate processing (in this case sorting) will not be performed.

这样做将已经使元素的副本,让你不

Doing this will already make a copy of the elements, so you don't actually need to create your own copy first.

Example:

例> INT [] = sortedCopy(从myArray的排序依据元素上行选择元素进行)
.ToArray();

int[] sortedCopy = (from element in myArray orderby element ascending select element) .ToArray();



这或许会是最好的表达语法来写:

It would perhaps be preferable to write this in expression syntax:

int[] sortedCopy = myArray.OrderBy(i => i).ToArray();

这篇关于排序与排序依据int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆