【发布时间】:2015-11-13 11:15:40
【问题描述】:
我正在尝试编写一个程序,它以非常优化的方式对时间进行排序。时间格式为HH:MM:SS 我从file.txt 读取数据,文件中的数据如下:
01:22:15 07:35:35 11:03:35 08:45:37 16:20:23 14:10:48 11:41:44 23:20:14 07:18:21 15:48:01 19:32:44 05:27:52 00:08:02 08:44:07 19:06:02 23:59:34 17:27:26
12:38:23 22:39:18 07:25:32 08:43:52
我必须逐行阅读并逐行打印排序后的输出。我最初考虑使用 Dictionary 并将 HH(小时)分配给键并按键排序,但**问题是,如果两个小时相同(我的意思是 12:56:59 已经存在)按键12 再次尝试添加12:23:44 按键12 ** 绝对例外)。
我的尝试是:
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = File.OpenText("C:\\Users\\ACER\\Desktop\\KT-iNDIA\\zExtra\\Bookprprn\\testCodeEval\\testCodeEval\\file.txt"))
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (null != line)
{
Dictionary<string, string> dictHH = new Dictionary<string, string>();
string[] digits = line.Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string digit in digits)
{
string[] eachdigit = digit.Split(new char[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries);
dictHH.Add(eachdigit[0], eachdigit[1] + " " + eachdigit[2]);
}
foreach (KeyValuePair<string, string> ch in dictHH.OrderBy(k => k.Key).Reverse())
{
Console.Write("{0} {1} ", ch.Key, ch.Value);
}
}
Console.WriteLine("");
}
Console.ReadKey();
}
}
如何解决问题?
【问题讨论】:
-
既然时间字符串是24H格式,而且是固定格式,为什么不能做一个普通的字符串排序呢?
-
为什么要使用 Dictionary
()?最好使用 List -
您正在迭代字典键,因此使用它没有性能优势。
-
@MatthewWatson 但在对字符串中的 HH 进行排序时,我必须与我保持 MM 和 SS,我将如何做到这一点。我的意思是,例如我拿了 List
dataHour;然后我做 dataHour.Sort();那么如何维护对应的MM和SS呢? -
只需对字符串进行排序即可。试试
Console.WriteLine(string.Join("\n", File.ReadLines(file).OrderBy(x => x)));,其中file是文件名。 (我假设每行有一次。)
标签: c# algorithm datetime dictionary data-structures