C# Array.FindIndex 当前对象的索引

标签 c# arrays linq indexing find

我正在做我的学校作业,这只是一个基本的编程练习,但此刻我被卡住了。我试图尽可能简单优雅地解决所有问题,而我的同学只是使用了一堆 for 循环,我认为这很恶心。我也可以这样做,这对我来说不是挑战,但我认为我应该按照它可以帮助我提高更多的方式去做。

所以任务是我们有一个 txt 文件,其中包含一些关于广播节目​​的数据。第一行告诉播放的所有歌曲的编号,之后的每一行由四个项目组成,广播 channel 的编号、歌曲的长度(分和秒)和歌曲的名称。我们必须能够阅读它,并根据它回答一些问题。我被困在以下地方:

"Tell exactly how much time went past since the beginning and the end of the first and last Eric Clapton song on radio channel #1."

文件看起来像这样:

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]));

嗯,它工作得很好,但问题是,它不是上述问题的答案,它只回答整个部分在所有三个 channel 上过去了多少时间。我如何实现它以仅搜索 channel #1 上的 channel ?是否可以在 FindIndex 方法本身中获取 x (对象)的当前索引?我应该改用 LINQ 吗?

请帮帮我,我发现这些单行方法非常干净,现在我面临一个我无法解决的问题。我也不知道。

最佳答案

我很欣赏你为让它变得更好而不仅仅是写几个循环所做的努力。但是,仍有改进的余地。

如果将歌曲存储在适当的类中,您的逻辑会变得更加清晰

public class Song
{
    public int Channel { get; set; }
    public TimeSpan Length { get; set; }
    public string Author { get; set; }
    public string Name { get; set; }
}

然后我会将歌曲存储在 Song 的数组中,因为您事先知道确切的记录数。否则一个List<Song>会更合适。

int n_lines = Convert.ToInt32(sr.ReadLine());
var songs = new Song[n_lines];
for (int i = 0; i < n_lines; i++) {
    string line = sr.ReadLine();
    string[] columns = line.Split(new char[] { ' ' }, 4);
    string[] subcolumns = columns[3].Split(':');
    int minutes = Convert.ToInt32(columns[1]);
    int seconds = Convert.ToInt32(columns[2]);
    songs[i] = new Song {
        Channel = Convert.ToInt32(columns[0]),
        Length = new TimeSpan(0, minutes, seconds),
        Author = subcolumns[0],
        Name = subcolumns[1]
    };
}

现在我们可以更轻松地制定查询:

int lastSongIndex = Array.FindLastIndex(songs, 
    s => s.Channel == 1 && s.Author == "Eric Clapton");
int totalSeconds = songs
    .SkipWhile(s => s.Channel != 1 || s.Author != "Eric Clapton")
    .Select((s, i) => new { Song = s, Index = i })
    .TakeWhile(x => x.Index <= lastSongIndex)
    .Sum(x => (int)x.Song.Length.TotalSeconds);

LINQ 的重载为 Select它提供项目的索引作为第二个参数。由此我们必须构建一个包含歌曲和索引的匿名类型。然后我们可以停止总结,直到我们到达最后一首歌的索引。但是,我们仍然需要 Array.FindLastIndex为了找到它。


LINQ 并没有让这里的生活变得更轻松,因为我们需要考虑以特定歌曲开头和结尾的歌曲。这需要使用 LINQ 的很多技巧,因为 LINQ 以严格的顺序逐一处理项目。因此,在这种情况下,一个好的旧 for 循环将非常合适。

关于C# Array.FindIndex 当前对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884565/

相关文章:

c# - 更改键盘的按键颜色 WP8

c# - Mono编译器(dmcs)如何引用DLL?

c# - LINQ 无法识别 select 子句中的连接表

c# - 使用 Linq,按某些属性对对象进行排序并选择前 2 个对象

java - 在 Java 中使用数组添加两个 10 位数字

c# - 如何将 XML 数据加载到数据结构中?

javascript - NodeWebkit - 部署应用程序

c# - 使向导导航不那么线性的简单算法

php - 从 PHP 数组编写 PDO 搜索查询

c++ - 用指针翻转数组