如何排序在Visual C#对象的数组? [英] How to sort an array of objects in Visual C#?
问题描述
我有两个成员都是整数值的对象。我做这些对象的数组。每个对象值填充有随机整数。
I have an object that has two members that are both integer values. I made an array of these objects. Each objects values are filled with random integers.
欲根据第一构件值的对象的数组进行排序。我会怎么做呢?
I want to sort the array of objects according to the first member value. How would I do this?
推荐答案
您使用.NET 3.5?如果是这样,这是因为容易
Are you using .NET 3.5? If so, it's as easy as:
array = array.OrderBy(x => x.MemberName).ToArray();
这将创建一个新的的阵列,虽然 - 如果任何其他code的老数组的引用,它仍然会看到未排序的数据
That will create a new array though - if any other code has a reference to the old array, it will still see the unsorted data.
另外,您也可以使用 的Array.Sort
方法,将就地对数组进行排序,以三种方式之一:
Alternatively, you can use the Array.Sort
method which will sort the array in-place, in one of three ways:
- 请您类型实施
IComparable的< T>
允许对象本身与另一 - 创建的
的IComparer℃的情况下,T>
它可以比较该类型的任何两个物体 - 创建类型
比较℃的代表; T>
它可以比较该类型的任何两个物体
- Make your type implement
IComparable<T>
allowing an object to compare itself with another - Create an instance of
IComparer<T>
which can compare any two objects of that type - Create a delegate of type
Comparison<T>
which can compare any two objects of that type
最后一个可能是,如果你使用C#3最简单的方法:
The last is probably the easiest solution if you're using C# 3:
Array.Sort(array, (x1, x2) => x1.MemberName.CompareTo(x2.MemberName));
这篇关于如何排序在Visual C#对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!