gpt4 book ai didi

c# - 为 UI 目的对枚举进行排序

转载 作者:可可西里 更新时间:2023-11-01 08:18:39 24 4
gpt4 key购买 nike

假设我们有一个 UI,在这个 UI 中我们有一个下拉菜单。此下拉列表中填充了枚举的翻译值。

恭喜,我们可以按枚举的 int 值、枚举的名称以及枚举的翻译名称进行排序。

但是如果我们想要与上述 3 种不同的排序方式呢?如何处理这样的需求?

最佳答案

实现你自己的IComparer:

using System;
using System.Collections.Generic;

namespace test {
class Program {

enum X {
one,
two,
three,
four
}

class XCompare : IComparer<X> {
public int Compare(X x, X y) {
// TBA: your criteria here
return x.ToString().Length - y.ToString().Length;
}
}


static void Main(string[] args) {
List<X> xs = new List<X>((X[])Enum.GetValues(typeof(X)));
xs.Sort(new XCompare());
foreach (X x in xs) {
Console.WriteLine(x);
}
}
}
}

关于c# - 为 UI 目的对枚举进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1299056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com