我有点麻烦了。我正在使用一个遗留系统,该系统包含一堆需要解析的分隔字符串。不幸的是,字符串需要根据字符串的第一部分进行排序。该数组如下所示
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";
我想做一个二维数组来抓取第一部分,而把字符串留在第二部分,但是我能在这样的二维数组中混合类型吗?
我不知道该如何处理这种情况,有人能帮上忙吗?谢谢!
发布于 2010-01-22 04:09:39
调用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));
}
}
或者,通过适当地拆分字符串,将字符串数组转换为自定义类型的数组。如果您要在数组上做进一步的工作,这将使工作变得更容易,但是如果您只需要对值进行排序,那么您最好使用上面的代码。
你确实说过你需要解析字符串-那么在排序之前你有什么特殊的理由想要解析它们吗?
发布于 2010-01-22 04:15:31
new[] {
"10|JohnSmith|82",
"1|MaryJane|62",
"3|TomJones|77",
}.OrderBy(x => int.Parse(x.Split('|')[0]));
发布于 2010-01-22 04:10:21
使用ArrayList (http://msdn.microsoft.com/en-us/library/system.collections.arraylist_methods(VS.80).aspx )以便对其进行排序。
https://stackoverflow.com/questions/2112454
复制相似问题