使用vb.net按日期在txt文件中排序

时间:2013-06-29 18:13:28

标签: vb.net date linq-to-xml

我创建了一个程序,从IMDB api获取发布日期和标题,并将它们保存在.txt文件中...我可以按日期以某种方式订购它们

enter image description here

Imports System.IO
Imports System.Xml.Linq
Imports System.Text.RegularExpressions

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim _reg As Regex = New Regex("http://www.imdb.com/title/([A-Za-z0-9\-]+)/*?", _
              RegexOptions.IgnoreCase)

        Dim value As String = TextBox1.Text

        Dim m As Match = _reg.Match(value)

        If (m.Success) Then
            Dim key As String = m.Groups(1).Value
            Dim url As String = "http://mymovieapi.com/?id=" + key + "&type=xml&plot=none&episode=0&lang=en-US&aka=simple&release=simple&business=0&tech=0"
            Dim Document As XDocument = XDocument.Load(url)
            Dim title = Document.Root.Element("title").Value()
            Dim releaseDate = Date.ParseExact(Document.Root.Element("release_date").Value,
                  "yyyyMMdd", System.Globalization.CultureInfo.InstalledUICulture)
            TextBox2.Text = "Release Date: " & releaseDate & "  /   Title: " & title
        Else : TextBox2.Text = "Please use IMDB links"
        End If
        Button2.Enabled = True
    End Sub


    Private Sub Button2_Click_1(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Dim Writer As System.IO.StreamWriter
        Writer = New System.IO.StreamWriter("C:\Users\Azer\Documents\Movies.txt", True)
        Writer.Write(TextBox2.Text & vbCrLf)
        Writer.Close()
        Button2.Enabled = False
    End Sub

    Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
        Dim Reader As System.IO.StreamReader
        Reader = New System.IO.StreamReader("C:\Users\Azer\Documents\Movies.txt")
        Dim tempstring As String
        Do
            tempstring = Reader.ReadLine()
            TextBox3.Text = TextBox3.Text + tempstring + vbCrLf
        Loop Until tempstring = ""
        Reader.Close()
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        Me.Close()
    End Sub

    Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
        TextBox3.Clear()
    End Sub
End Class

2 个答案:

答案 0 :(得分:2)

正如大卫所说,数据库会让这更容易。但是,如果你不能使用数据库(或者有其他理由这样做的话),这是接近它的一种方法。

创建一个包含信息的小类(以便更容易排序,如下所示:

Public Class MovieInfo

    Public Property As DateTime
    Public Title As String
End Class

接下来,读取当前文件(如果存在)并使用其中的数据填充List<MovieInfo>

Dim movies As String() = File.ReadAllLines("C:\Users\Azer\Documents\Movies.txt")

Dim movieParts = From m in movies
                 Select m.Split(New String() { "/", ":" }, StringSplitOptions.RemoveEmptyEntries)

Dim parsedDate As DateTime

Dim movieData As List(Of MovieInfo) = (From mi In movieParts
                                       Select New MovieInfo With
                                       {
                                           .ReleaseDate = _
      If(DateTime.TryParseExact(mi(1).Trim, "dd.MM.yyyy", _
         System.Globalization.CultureInfo.InvariantCulture, _
         System.Globalization.DateTimStyle.None, _
         parsedDate), parsedDate, DateTime.MinValue),
                                           .Title = mi(3).Trim()
                                       }.ToList()

基本上上面的代码将文本文件读入一个数组(每个元素一行),然后使用LINQ将每行分成4个部分,基于:和/。然后它获取该查询的结果并构建一个MovieInfo列表,将日期字符串转换为DateTime以便于排序。

DateTime.TryParseExact获取指定格式的输入字符串(在本例中为dd.MM.yyyy),如果可能,将其转换为DateTime对象。如果成功,则返回true,DateTime值在parsedDate变量中。如果不是这样,我使用MinValue for DateTime作为MovieInfo类的ReleaseDate属性。

之后,您将从API调用中获取新数据并将其添加到MovieInfo列表中(您可能希望消除任何重复项)。由于您没有从API发布数据格式,因此我很难给您一个代码示例来解析它,但简而言之,您可以构建第二个MovieInfo对象列表,然后合并现有和新的一起列出。

然后,您对MovieInfo列表进行排序并覆盖原始文本文件。这样的事情可以解决问题:

movieData.Sort(Function(x, y) y.ReleaseDate.CompareTo(x.ReleaseDate))

Dim output As New StringBuilder()

For Each info As MovieInfo in movieData
    output.Append("Release Date: ")
    output.Append(info.ReleaseDate.ToString("dd.MM.yyyy"))
    output.Append(" / Title: ")
    output.Append(info.Title)
    output.Append(Enviroment.NewLine)
Next

File.WriteAllText("C:\Users\Azer\Documents\Movies.txt", output.ToString())

此代码使用lambda表达式对列表进行排序,以按日期顺序(最新到最旧)放置电影。然后它使用带有For Each循环的StringBuilder来构建输出,然后将其写入文件(如果文件已存在则覆盖该文件)。

请注意,如果您在排序中反转x和y,则按日期最新到最新。

答案 1 :(得分:-1)

Dim allLines As String() = File.ReadAllLines("your file name")
System.Array.Sort(allLines)
IO.File.WriteAllLines("your file name", allLines) 'assuming you want to write the file