gpt4 book ai didi

c# - 如何在 C# 中对分隔字符串数组进行数字排序

转载 作者:太空狗 更新时间:2023-10-29 22:05:58 24 4
gpt4 key购买 nike

我有点手足无措。我正在使用一个遗留系统,其中包含一堆我需要解析的分隔字符串。不幸的是,字符串需要根据字符串的第一部分进行排序。该数组看起来像

array[0] = "10|JohnSmith|82";
array[1] = "1|MaryJane|62";
array[2] = "3|TomJones|77";

所以我希望数组排序看起来像

array[0] = "1|MaryJane|62";
array[1] = "3|TomJones|77";
array[2] = "10|JohnSmith|82";

我想过做一个二维数组来获取第一部分并将字符串留在第二部分,但是我可以像这样在二维数组中混合类型吗?

我不确定如何处理这种情况,有人可以帮忙吗?谢谢!

最佳答案

调用Array.Sort , 但传入 IComparer<string> 的自定义实现:

// Give it a proper name really :)
public class IndexComparer : IComparer<string>
{
public int Compare(string first, string second)
{
// I'll leave you to decide what to do if the format is wrong
int firstIndex = GetIndex(first);
int secondIndex = GetIndex(second);
return firstIndex.CompareTo(secondIndex);
}

private static int GetIndex(string text)
{
int pipeIndex = text.IndexOf('|');
return int.Parse(text.Substring(0, pipeIndex));
}
}

或者,通过适当拆分字符串,将字符串数组转换为自定义类型数组。如果您要对数组做进一步的工作,这将使生活更轻松,但如果您需要对值进行排序,那么您不妨使用上面的代码。

您确实说过您需要解析字符串 - 那么您是否有任何特殊原因想要在对它们进行排序之前解析它们?

关于c# - 如何在 C# 中对分隔字符串数组进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2112454/

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