【发布时间】:2014-04-05 17:55:38
【问题描述】:
我正在做我的学校作业,这只是一个基本的编程练习,而现在我被困住了。我试图尽可能简单优雅地解决所有问题,而我的同学只是使用了一堆 for 循环,我认为这很恶心。我也可以这样做,这对我来说不是挑战,但我认为我应该这样做有助于我进一步提高。
所以任务是我们有一个 txt 文件,其中包含一些有关广播节目的数据。第一行告诉播放的所有歌曲的数量,之后的每一行由四个项目组成,广播频道的数量,歌曲的长度(分钟和秒)和歌曲的名称。我们必须能够阅读它,并根据它回答一些问题。我陷入了以下困境:
“准确说出从开始到结束过去了多少时间 广播频道 #1 的第一首也是最后一首 Eric Clapton 歌曲。”
文件如下所示:
677
1 5 3 Deep Purple:Bad Attitude
2 3 36 Eric Clapton:Terraplane Blues
3 2 46 Eric Clapton:Crazy Country Hop
3 3 25 Omega:Ablakok
2 4 23 Eric Clapton:Catch Me If You Can
1 3 27 Eric Clapton:Willie And The Hand Jive
3 4 33 Omega:A szamuzott
2 6 20 Eric Clapton:Old love
...
我用这段代码读过它:
const int N_COL = 4;
const int N_ROW = 1000;
string[][] RDATA = new string[N_COL][];
for (int i = 0; i < N_COL; i++)
RDATA[i] = new string[N_ROW];
using (StreamReader sr = new StreamReader("musor.txt"))
{
int n_lines = Convert.ToInt32(sr.ReadLine());
for (int i = 0; i < n_lines; i++)
{
int idx = 0;
foreach (string s in (sr.ReadLine().Split(new char[] {' '}, 4)))
RDATA[idx++][i] = s;
}
}
这就是我试图回答这个问题的方式:
int[] first = new int[] { Array.FindIndex(RDATA[3], x => x.Contains("Eric Clapton")), 0 };
int[] last = new int[] { Array.FindLastIndex(RDATA[3], RDATA[3].Count(x => x != null) - 1, x => x.Contains("Eric Clapton")), 0 };
for (int i = 0; i < first[0]; i++)
if (RDATA[0][i] == RDATA[0][first[0]])
first[1] += Convert.ToInt32(RDATA[1][i]) * 60 + Convert.ToInt32(RDATA[2][i]);
for (int i = 0; i <= last[0]; i++)
if (RDATA[0][i] == RDATA[0][last[0]])
last[1] += Convert.ToInt32(RDATA[1][i]) * 60 + Convert.ToInt32(RDATA[2][i]);
Console.WriteLine("\nDifference: {0}", TimeSpan.FromSeconds(last[1] - first[1]));
嗯,它工作得很好,但问题是,它不是上述问题的答案,它只回答了整个部分过去了多少时间,在所有三个频道上。我怎样才能实现它来只搜索频道#1 上的那些?是否可以在 FindIndex 方法本身中获取 x (对象)的当前索引?我应该改用 LINQ 吗?
请帮帮我,我发现这些单行方法很干净,现在我面临一个我无法解决的问题。我也不知道。
【问题讨论】:
-
我的第一个建议是重构您当前必须使用的类,每个数据项都有一个属性。
string [][]让人很难理解。
标签: c# arrays linq indexing find