我有点受约束.我正在使用遗留系统,其中包含一堆我需要解析的分隔字符串.不幸的是,字符串需要根据字符串的第一部分进行排序.该数组看起来像
array[0] = "10|JohnSmith|82";
array[1] = "1|MaryJane|62";
array[2] = "3|TomJones|77";
Run Code Online (Sandbox Code Playgroud)
所以我想让数组看起来像
array[0] = "1|MaryJane|62";
array[1] = "3|TomJones|77";
array[2] = "10|JohnSmith|82";
Run Code Online (Sandbox Code Playgroud)
我想过做一个2维数组来抓住第一部分并将字符串留在第二部分,但是我可以在这样的二维数组中混合类型吗?
我不确定如何处理这种情况,有人可以帮忙吗?谢谢!
Jon*_*eet 13
调用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));
}
}
Run Code Online (Sandbox Code Playgroud)
或者,通过适当地拆分字符串,将字符串数组转换为自定义类型数组.如果你要对数组做进一步的工作,这将使生活更轻松,但如果你只需要对值进行排序,那么你也可以使用上面的代码.
你确实说你需要解析字符串 - 所以你有什么特别的理由要在解码之前解析它们吗?
new[] {
"10|JohnSmith|82",
"1|MaryJane|62",
"3|TomJones|77",
}.OrderBy(x => int.Parse(x.Split('|')[0]));
Run Code Online (Sandbox Code Playgroud)