gpt4 book ai didi

c# - 基于整数顺序的字符串列表排序

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:35 25 4
gpt4 key购买 nike

我有列表。尽管数据类型为字符串,但此列表仅包含整数值。我想根据项目的整数顺序对列表进行排序。

如何实现?

List<string> newZipCodesList = new List<string>();

最佳答案

您可以使用 IComparer 接口(interface)来实现您自己的排序。您将必须创建一个类,该类将实现 T 的 IComparer,其中 T 在本例中为字符串。

   newZipCodesList.Sort(new Test());

public class Test : IComparer<string>
{
public int Compare(string x, string y)
{
//return 1 when first is greater than second
if(Convert.ToInt32(x) > Convert.ToInt32(y))
return 1;
//return -1 when first is less than second
else if (Convert.ToInt32(x) < Convert.ToInt32(y))
return -1;
//return 0 if they are equal
else
return 0;
}
}

关于c# - 基于整数顺序的字符串列表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889992/

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