gpt4 book ai didi

c# - 给定所需的排序层次结构,如何自定义对字符串列表进行排序?

转载 作者:行者123 更新时间:2023-12-04 00:57:33 24 4
gpt4 key购买 nike

我想对 List<string> 进行排序以特定的方式。下面是一个单元测试,显示了输入具体方式(我称之为“层次结构”——随时纠正我的术语以便我学习),以及所需的输出。代码应该是不言自明的。

[Test]
public void CustomSortByHierarchy()
{
List<string> input = new List<string>{"TJ", "DJ", "HR", "HR", "TJ"};

List<string> hierarchy = new List<string>{"HR", "TJ", "DJ" };

List<string> sorted = input.Sort(hierarchy); // <-- does not compile. How do I sort by the hierarchy?

// ...and if the sort worked as desired, these assert statements would return true:
Assert.AreEqual("HR", sorted[0]);
Assert.AreEqual("HR", sorted[1]);
Assert.AreEqual("TJ", sorted[2]);
Assert.AreEqual("TJ", sorted[3]);
Assert.AreEqual("DJ", sorted[4]);
}

最佳答案

另一种方法:

var hierarchy = new Dictionary<string, int>{
{ "HR", 1},
{ "TJ", 2},
{ "DJ", 3} };

var sorted = strings.OrderBy(s => hierarchy[s]).ToList();

关于c# - 给定所需的排序层次结构,如何自定义对字符串列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61237975/

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