2014-11-18 2 views
1

VB.NET 2010을 사용 중이며 순차 파일을 사용하여 검색 기능을 구현하려고합니다. 원래 순차 파일을 사용하여 읽기 및 검색을 시도했지만 극히 어려웠으므로 데이터가있는 두 개의 다른 배열을 사용하고 아티스트 및 앨범을 검색하려고 간단한 접근 방식을 취했습니다.순차 파일로드 배열 검색 및 검색

아래 코드는 아티스트 검색을위한 txtSearch.Text의 입력을 사용합니다. 필자는 중복 된 아티스트 "TeeBee"를 가지고 있지만 그 아티스트를 검색 할 때 아티스트 "TeeBee"아래에 두 개의 다른 앨범이 있으므로 두 개가 아닌 하나의 결과 만 수신합니다.

다른 루프를 추가하려고 생각했지만 작동하지 않습니다. 결과에 대한 수익을 계속할 수있는 방법이 없기 때문에 결과가 잘려나 가고 있다고 생각했습니다.

저는 초보자이므로 프로그래밍을 염두에 두시기 바랍니다.

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click 

    ' Artist array 
    Dim strArtist() As String = {"Dillinja", "TeeBee", "Dieselboy", "TeeBee"} 
    ' Album array 
    Dim strAlbum() As String = {"Untitled", "Scorpion", "Horns", "Blades"} 

    Dim strSearchForArtist As String 
    Dim intSub As Integer 

    ' artist search 
    strSearchForArtist = txtSearch.Text 

    Do Until intSub = strAlbum.Length OrElse 
     strSearchForArtist = strArtist(intSub) 
     intSub = intSub + 1 
    Loop 

    If intSub < strArtist.Length Then 
     lstLibrary.Items.Add(strArtist(intSub) & " " & strAlbum(intSub) & vbNewLine) 
    Else 
     MessageBox.Show("Invalid", "Bad", MessageBoxButtons.OK, MessageBoxIcon.Information) 
    End If 

End Sub 

배열에 텍스트 파일을로드하려고하지만, 앨범, 아티스트 장르와 같은 별도의 배열을 만들지 않습니다. - 11-19-14


개인 서브 btnLoadArray_Click (개체로 보낸 사람, EventArgs입니다으로 전자) 문자열 = "library.txt"배열보다는

Dim sr As IO.StreamReader 
    sr = IO.File.OpenText(filePath) 

    ' look inside file and read every line 
    ' this will be how we put the number for 
    ' our array below 
    Dim TotalLines As Integer = 0 

    Dim word As String = "" 
    ' need 3 to be dynamic so we get all lines in the file to build the array words(#) 
    ' wanted to use words(,) but that does not work 
    Dim words() As String = IO.File.ReadAllLines(filePath) 
    Dim i As Integer = 0 

    ' when the peak value is -1 we're at the end of the file 
    Do Until sr.Peek = -1 
     ' load one at a time 
     word = sr.ReadLine() 
     ' load word into array 
     words(i) = word 

     ' output 
     lstArtist.Items.Add(words(i)) 
     ' increment counter 
     i += 1 
    Loop 

    'close the file 
    sr.Close() 
End Sub 
+2

왜 클래스를 사용하여 별도의 배열 대신 커플 아티스트/앨범을 나타내지 않습니까? – Steve

답변

0

으로 btnLoadArray.Click 희미한 파일 경로를 처리 , List(of String)은 관리가 쉽고 더 많은 효율성과 기능을 제공합니다.

Private Artists As New List(of String) 

.... 
Artists.Addrange({"Dillinja", "TeeBee", "Dieselboy", "TeeBee"}) 
... 
' find a single item: 
If Artists.Contains(txtSearch.Text) Then  ' no looping required 
    ' a dupe 
Else 
    ' not a dupe 
End If 

는 일치하는 모든 항목을 얻으려면 :

Dim find = Artists.Where(Function(s) _ 
    s.ToLowerInvariant = txtSearch.Text.ToLowerInvariant).ToList 

결과 find도 일치하는 항목을 포함 (문자열의)리스트가 될 것입니다. 이번에는 대소 문자를 구분하지 않습니다. 나도이 얼마나 많은 가치 몰라요

Dim finds = Artists.LongCount(Function(n) n.ToLowerInvariant = _ 
     txtSearch.Text.ToLowerInvariant.ToLowerInvariant) 

다음 수 속는의를 얻을 수 있습니다. 2도 아니고 "Teebee", "TeeBee"도 매우 유용하거나 흥미 롭습니다. 보다 일반적으로 검색 용어와 연관된 전체 객체 (앨범과 같은)로 돌아 가기를 원합니다. Arist, Album, Genere, Tracks 등을 함께 묶는 Class가 필요합니다 (이 부분에 대한 Steve의 답변 참조).

전체 파일 부분에 대해 목록을 쉽게 직렬화하여 2-3 줄의 코드로 전체 목록을 디스크에서 저장하거나 다시로드 할 수 있습니다.

+0

나는 내가 겪고있는 문제의 일부가 내가 문제를 생각하고 끝났다고 생각한다. 그리고 내가 배운 것에 대한 책은 오히려 부실하며, 무슨 일이 일어나고 있는지에 관해서는 예의 바른 예와 분명한 설명이 부족하다. 필자는 각 행에 여러 항목이있는 텍스트 파일에서 배열을 만드는 독창적 인 아이디어를 다시 방문했습니다. 본질적으로 내가 할 수는 있었지만 각 항목을 구문 분석했지만 책은 쉼표로 구분 된 파일을 넘기거나 행의 각 항목을 아티스트 이름 앨범 제목 장르와 다음 줄로 구분하는 공백을 검색하지 않았습니다. – VanCoon

1

음, 대신 배열을 사용하고 정말 좋습니다 모든 합병증을 처리 당신은 더 객체 지향 접근 방식을 가지고

그래서이

Public Class Album 
    Public ArtistName as String 
    Public AlbumTitle as String 
    Public Function ToString() as String 
     return ArtistName & " - " & AlbumTitle 
    End Function 
End Class 
같은 앨범에 대한 정보를 유지하는 클래스를 정의 시작

List(Of Album)을 사용하여 배열 엉망을 제거하고이 목록의 각 항목에 ToString 방법을 통해 콘텐츠를 렌더링하도록 요청할 수 있습니다.

중요한 역할은 List (Of Album)에서 Where 메서드에 필요한 Lambda expression을 존중하는 모든 요소를 ​​추출하는 IEnumerable function Where에 예약되어 있습니다.

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click 

    ' Here the list is fixed but you can easily build it loading data from a database 
    ' or from some other storage medium like a file etc... 
    Dim albumList = new List(Of Album) From _ 
    { 
     new Album With { .ArtistName = "Dillinja", .AlbumTitle = "Untitled" }, 
     new Album With { .ArtistName = "TeeBee", .AlbumTitle = "Scorpion"}, 
     new Album With { .ArtistName = "Dieselboy", .AlbumTitle = "Horns" }, 
     new Album With { .ArtistName = "TeeBee", .AlbumTitle = "Blades" } 
    } 

    ' To help search you could integrate the ToLower expressions in 
    ' Plutonix answer here... 
    Dim searchTerm = txtSearch.Text 
    Dim searchResult = albumList.Where(Function(x) x.ArtistName = searchTerm) 

    lstLibrary.Items.Clear() 
    if searchResult.Count > 0 Then 
     For Each item in searchResult 
      lstLibrary.Items.Add(item.ToString()) 
     Next 
    Else 
     MessageBox.Show("Not found") 
    End if 
End Sub