如何使用Array.sort通过特定元素对结构数组进行排序 [英] How to use Array.sort to sort an array of structs, by a specific element
本文介绍了如何使用Array.sort通过特定元素对结构数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单,我有一个像这样的结构:
Simple, I have a struct like this:
struct bla{
string name;
float depth;
}
我有一个bla数组,我想按深度排序,首先是最大深度. 代表应该做/返回什么?我找不到任何具体的例子.
I have an bla array, and I want to sort by depth, being the greatest depth first. What should the delegate do/return? I cant find any concrete example.
推荐答案
您可以使用 Comparison<T>
:
You can use the overload of Array.Sort
which takes a Comparison<T>
:
bla[] blas = new[] {
new bla() { name = "3", depth = 3 },
new bla() { name = "4", depth = 4 },
new bla() { name = "2", depth = 2 },
new bla() { name = "1", depth = 1 },
};
Array.Sort<bla>(blas, (x,y) => x.depth.CompareTo(y.depth));
通过这种方式,您可以对原始数组进行排序,而不是创建新数组.
On this way you sort the original array instead of creating new one.
这篇关于如何使用Array.sort通过特定元素对结构数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文